try this :-
carprice['fueltype']=carprice['fueltype'].map({'gas':1,'diesel':0})
or you can do
carprice['fueltype']=carprice['fueltype'].apply(lambda x: 1 if x =='gas' else 0))
Map basically operates on the series while apply works on each cell.
Answer from Yash Thenuan on Stack Overflowtry this :-
carprice['fueltype']=carprice['fueltype'].map({'gas':1,'diesel':0})
or you can do
carprice['fueltype']=carprice['fueltype'].apply(lambda x: 1 if x =='gas' else 0))
Map basically operates on the series while apply works on each cell.
Map function with in "apply" works fine if your column is of dataframe type rather than a series. To convert a column from series to dataframe enclose it with in '[]'
carprice[['fueltype']]=carprice[['fueltype']].apply(lambda x: x.map({'gas':1,'diesel':0}))
Sequence of Map - `AttributeError: 'str' object has no attribute 'items'`` when data contains Map in Map
AttributeError: 'str' object has no attribute 'fetch'
AttributeError: 'str' object has no attribute 'get'
How do i fix this : AttributeError: 'str' object has no attribute 'current'
I have some experience with programming in Java, C++, etc. and I am trying to write a simple "To-Do List" program to get used to Python. I'm running into the error: str object has no attribute "completed" when trying to iterate over the list of tasks, check their completion status, and display them.
Here are some relevant pieces of the program:
Constructor for the Task class
def __init__(self, task_name):
self.task_name = task_name
self.completed = False
In the ToDoList class (which holds a list of the task instances created by the user) this is the iteration throwing the error in question:
for idx, task in enumerate(self.tasks, start=1):
status = "Completed" if task.completed else "Incomplete"
print(f"{idx}. {task.task_name} - {status}")
I thought, potentially the problem lies in the fact that the enumerate function is grabbing the string value of the task instance, rather than the object itself, so maybe I can iterate over it the old fashioned way and get around it. So I tried it like this:
counter = 1
for task in self.tasks:
status = "Completed" if task.completed else "Incomplete"
print(f"{counter}. {task.task_name} - {status}")
counter += 1
Yet, it throws the same error. I know there is something I am missing or not understanding correctly here. What is it?
Thanks!
There is something wrong with this function. It shows no errors, but when I try to run it, It says AttributeError: 'str' object has no attribute 'current'. (BTW, i am trying to run it as a flet on spyder)
def leapyears(e):
days_in_month = {1: 31, 3: 31, 4: 30, 5:31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 }
month = int(EnterMonth_text.value)
year = int(EnterYear_text.value)
if year % 100 == 0:
if year % 400 == 0:
leap_year = True
elif year % 4 == 0:
leap_year = True
else:
leap_year = False
if month == 2 :
if leap_year:
days_in_month[2] = 29
else:
days_in_month[2]= 28
output_textfield.value= days_in_month[month]
page.update()
I'm not sure why you're using map here. Iterating over a dictionary gives you the keys only, which are strings. Just use the dict directly; you don't need lambda either:
my_dict.get('a').get('b')
(As noted in the comments, you shouldn't use dict as the name of your variable.)
When you access a dictionary d as an iterator, you iterate over the keys. You are essentially doing
dict(map(lambda x:x.get('a').get('b'), ['a']))
If some of your interfaceCounters keys reference a string instead of a nested dictionary, just use exception handling to ignore those:
for keys in interfaces:
counters = interfaces[keys].get(u'interfaceCounters', {})
try:
print keys, "inOctets:", counters.get(u'inOctets', {}), "outOctets:", counters.get(u'outOctets', {})
except AttributeError:
# counters is not a dictionary, ignore and move on
pass
This is the ask forgiveness principle; if most of your entries do have the .get() method this is simply faster than the look before you leap principle, where you test if the method is available.
How about simply checking if your dictionary value does provide the method/attribute you need?
for keys in interfaces:
counters = interfaces[keys].get(u'interfaceCounters', {})
if hasattr(counters, 'get'):
# Only print if counters supports `get`
print keys, "inOctets:", counters.get(u'inOctets', {}), "outOctets:", counters.get(u'outOctets', {})
The error means exactly what it says:
AttributeError: 'str' object has no attribute 'DataFrame'
^ ^ ^
the kind of error | |
the thing you tried to use what was missing from it
The line it's complaining about:
df = pd.DataFrame(date, columns = ['Date'])
^ ^
| the attribute the error said was missing
the thing the error said was a string
has been working no problem until I added a few lines of code above
Evidently, somewhere in the "few lines of code above", you caused pd to be a string. And sure enough, when we look at those few lines of code, we find:
pd = PDays[j]
^ ^
| the string that you're making it into
the thing that you're making a string
You are reassign pd
import pandas as pd
to
pd = PDays[j]