Python how to fill zeros in data frame using dictionary
I have a dataframe df something like this
A B C
1 'x' 15.0
2 'y' NA
3 'z' 25.0
and the dc dictionary is something like
dc = {'x':15,'y':35,'z':25}
I want to fill in all zeros in column C of a dataframe using the values ββof column B from a dictionary. So that my dataframe becomes
A B C
1 'x' 15
2 'y' 35
3 'z' 25
Can anyone help me how to do this?
thanks Manoi
+3
Manoj agrawal
source
to share
2 answers
You can use fillna
with map
:
dc = {'x':15,'y':35,'z':25}
df['C'] = df.C.fillna(df.B.map(dc))
df
# A B C
#0 1 x 15.0
#1 2 y 35.0
#2 3 z 25.0
+4
Psidom
source
to share
df['C'] = np.where(df['C'].isnull(), df['B'].apply(lambda x: dc[x]), df['C'])
+3
DyZ
source
to share