How To Conditionally Update Dataframe Column In Pandas Based On List
Supposed I have a dataframe with one column: df = pd.DataFrame(np.random.randint(0,9,size=(100, 1)), columns=['number']) I have two lists, one list containing even numbers, the ot
Solution 1:
I think you can use numpy.where
:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,9,size=(100, 1)), columns=['number'])
df['odd_or_even'] = np.where(df.number % 2, 'odd', 'even')
print (df)
number odd_or_even
01 odd
10 even
24 even
35 odd
40 even
50 even
61 odd
70 even
87 odd
98 even
EDIT by comment
Use loc
:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,9,size=(20, 1)), columns=['number'])
odd_numbers = [1,3,5,7,9]
even_numbers = [0,2,4,6,8]
df.loc[df.number.isin(odd_numbers), 'odd_or_even'] = 'odd'
df.loc[df.number.isin(even_numbers), 'odd_or_even'] = 'even'print (df)
number odd_or_even
05 odd
11 odd
22 even
33 odd
45 odd
56 even
63 odd
74 even
82 even
98 even
108 even
111 odd
122 even
131 odd
143 odd
153 odd
165 odd
174 even
182 even
195 odd
Solution 2:
A map version:
First, create a dictionary:
d = {**{o: "odd" for o in odd_numbers}, **{e: "even" for e in even_numbers}}
Then use map on the series:
df['odd_or_even'] = df['number'].map(d)
Post a Comment for "How To Conditionally Update Dataframe Column In Pandas Based On List"