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



如果已经询问并回答了这个问题,但搜索了一整天却找不到正确的解决方案,请道歉。如果解决方案已经存在,请告诉我。

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

任何panda方式都会很好,以避免在给定实际数据帧大小的情况下进行迭代循环。

我尝试过使用combinefirst和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

最新更新