Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

python - How to insert the values of dictionary into null values of a dataframe in pandas?

I am new to pandas. I am facing an issue with null values. I have a dict of 3 values and keys which has to be inserted into a column of missing values how do I do that? The last word key is the name of the column name

In [57]: df
Out[57]: 
   a   b   c  d  
0  0   1   2  3  
1  0 NaN   0  1  
2  0 Nan   3  Nan 
3  0   1   2  5  
4  0 Nan   2  Nan 
In [58]: dict= {df_b : [11,22,44], df_d: [33,54]

The output I want is below.

Out[57]: 
   a   b   c  d  
0  0   1   2  3  
1  0   11  0  1  
2  0   22  3  33 
3  0   1   2  5  
4  0   44  2  54
question from:https://stackoverflow.com/questions/65906814/how-to-insert-the-values-of-dictionary-into-null-values-of-a-dataframe-in-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given your data

d = [[0,   1,   2,  3  ],
[0, np.nan,   0,  1  ],
[0, np.nan,   3,  np.nan], 
[0,   1,   2,  5  ],
[0, np.nan,   2,  np.nan]] ]
df = pd.DataFrame(d, columns=['a', 'b', 'c', 'd'])
d = {'df_b' : [11,22,44], 'df_d': [33,54]}

try pandas.isna()

for key in d:
    column_name = key.split('_')[-1]
    val = d[key]
    for i,v in zip(df[df[column_name].isna()].index, val):
        df.loc[i, column_name] = v

output

a   b     c    d
0   1.0   2   3.0
0   11.0  0   1.0
0   22.0  3   33.0
0   1.0   2   5.0
0   44.0  2   54.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...