如何为列中的所有空值(NaN)获取存在于不同数据帧中的相应值?

2024-04-23 11:34:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个需要赋值的带有NaN值的数据帧。分配这些值的方式取决于“code”列。NaN值存在于不同的数据帧和同一列“code”中。你知道吗

我的初始数据帧具有NaN值,但不是在所有行中(第三行具有'capital'和'country'列的值: enter image description here

我想从下面的数据框中赋值: enter image description here

最终结果如下: enter image description here

我试过:

df1['capital'] = np.where(df1['capital'].isnull() == True, df1['code'].map(df2['capital']), df1['capital']

但我得到一个语法错误:“关键字不能是表达式”。你知道吗

你知道怎么克服吗?你知道吗


Tags: 数据truemapnp方式codenanwhere
1条回答
网友
1楼 · 发布于 2024-04-23 11:34:29

IIUC公司

方案1

df1.columns=df2.columns
pd.concat([df1,df2],axis=0).dropna(axis=0)

方案2

df1.set_index('code').captial.fillna(df2.set_index('col2').captial)
Out[184]: 
code
0    B
1    C
2    A
3    D
4    E
Name: captial, dtype: object

数据输入:

d1 = {'code' : [0,1,2,3,4],
         'captial' : [np.nan,np.nan,'A',np.nan,np.nan]}
df1 = pd.DataFrame(d1)
d2 = {'col2' : [0,1,3,4],
         'captial' : ['B','C','D','E']}
df2 = pd.DataFrame(d2)

相关问题 更多 >