Skip to content Skip to sidebar Skip to footer

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 a a dataframe (df) and I want to set a value (some_value) if a value from the colum

Solution 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

Post a Comment for "How To Set Values Based On A List In Pandas (python)"