简体   繁体   中英

How to set values based on a list in Pandas (python)

I have a maybe a hopefully easy question that I wasn't able to find an answer on stack.

I have aa dataframe (df) and I want to set a value (some_value) if a value from the column 'month' is in a list (some_list).

eg

 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.

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, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM