问题
I have a maybe a hopefully easy question that I wasn't able to find an answer on stack.
I have a a dataframe (df) and I want to set a value (some_value) if a value from the column 'month' is in a list (some_list).
e.g.
df[df['month'].isin(some_list)] = some_value
It's barfing up an AttributeError: 'int' object has no attribute 'view'.
Any helpful direction would be awesome.
[edit]:
some_list = [4,5,6,7]
some_value = 100
df.month is a value from 1 - 12
df.columns = ['datetime','weekday','hour','month','value']
I realize I also want to find out the index of the rows which isin some_list then use those indices to set the value of another column ('value') to some_value. Apologies for not writing that originally.
回答1:
Your question still doesn't seem to have enough information to find the real problem. This quick example shows that your attempt can work just fine:
import pandas as pd
df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})
some_list = [2, 3]
df[df['month'].isin(some_list)] = 99
df
Out[13]:
month x
0 1 4
1 99 99
2 99 99
...suggesting that your problem is more likely because you've mixed up the types of your variables. Currently the only thing I can suggest is only doing the assignment to specific columns, as you may be trying to assign an int value to a datetime column or something, e.g.:
df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})
some_list = [2, 3]
df.loc[df['month'].isin(some_list), 'x'] = 99
df
Out[14]:
month x
0 1 4
1 2 99
2 3 99
来源:https://stackoverflow.com/questions/31128477/how-to-set-values-based-on-a-list-in-pandas-python