python - 在df2.col2的基础上,在df.col1中填写na。两个数据帧的大小不同

标签 python pandas

如果已经询问并回复了此问题,但搜索了一整天但无法找到正确的解决方案,我们深表歉意。如果解决方案已经存在,请指出我的方向。

我正在尝试在 pandas 数据框(df1)的列中填充 na/nan 值。填充值位于另一个数据帧(df2)中,其中包含唯一的 id 和相应的值。我如何匹配df1.Prod_id的id(其中df.item_wt中的现有值为nan),然后在df2.mean_wt中找到相应的值并将nan值填充到df1.item_wt中。两个数据帧的大小不同,df1 有 80k+ 行,df2 只有 1559 行。列名也不同,因为来自不同的源。填充必须就地完成。

希望有任何 Pandas 方式,以避免给定实际数据帧大小的迭代循环。

我尝试使用combine_first和map,但成功率为零,因为数据帧大小不同,因此额外的行无法替换。

data1 = {'Prod_id':['PR1', 'PR2', 'PR3', 'PR4', 'PR2', 'PR3','PR1', 'PR4"],store=['store1','store2','store3','store6','store3','store8','store45','store23']'item_wt':[28,nan,29,42,nan,34,87,nan]}
df1 = pd.DataFrame(data1)

data2 = {'Item_name':['PR1', 'PR2', 'PR3', 'PR4'],'mean_wt':[18,12,22,9]}
df2 = pd.DataFrame(data2)

final df should be like:
data1 = {'Prod_id':['PR1', 'PR2', 'PR3', 'PR4', 'PR2', 'PR3','PR1', 'PR4"],store=['store1','store2','store3','store6','store3','store8','store45','store23']'Item_wt':[28,12,29,42,12,34,87,9]}
df1 = pd.DataFrame(data1)

最佳答案

您可以使用fillna并设置由 values 创建的 numpy 数组,因为原始系列和新系列的索引不同:

df1['item_wt'] = (df1.set_index('Prod_id')['item_wt']
                     .fillna(df2.set_index('Item_name')['mean_wt']).values)
print (df1)
  Prod_id    store  item_wt
0     PR1   store1     28.0
1     PR2   store2     12.0
2     PR3   store3     29.0
3     PR4   store6     42.0
4     PR2   store3     12.0
5     PR3   store8     34.0
6     PR1  store45     87.0
7     PR4  store23      9.0

或者使用map第一:

s = df2.set_index('Item_name')['mean_wt']
df1['item_wt'] = df1['item_wt'].fillna(df1['Prod_id'].map(s))
#alternative
#df1['item_wt'] = df1['item_wt'].combine_first(df1['Prod_id'].map(s))
print (df1)
  Prod_id    store  item_wt
0     PR1   store1     28.0
1     PR2   store2     12.0
2     PR3   store3     29.0
3     PR4   store6     42.0
4     PR2   store3     12.0
5     PR3   store8     34.0
6     PR1  store45     87.0
7     PR4  store23      9.0

关于python - 在df2.col2的基础上,在df.col1中填写na。两个数据帧的大小不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54086273/

相关文章:

python - 单个Python脚本的Azure函数部署以及Azure Functions中requirements.txt的安装过程

python - 如何使用 python 在 SQL select 语句中插入今天的日期?

python - 从列表中删除项目 - 在迭代期间 - 这个习语有什么问题?

python - 项目数较多的 QComboBox 初始显示性能缓慢

python - : bad interpreter: No such file or directory in python

python - 通过连接传播 pandas 系列元数据

python - jupyter 按顺序打印图和数据框,for 循环

python - pandas left join - 为什么会有更多结果?

python - pandas 0.21.0 时间戳与 matplotlib 的兼容性问题

python - salt 定制 Cereal