2016-11-30 75 views
0

假设我有以下的数据帧称为mapping_df如何用另一列中的修改值替换一列中的空值?

mapping | store_id 
--------|--------- 
    a | 1 
    b | 2 
     | 3 
    c | 4 
     | 5 

我想修改它,这样我就可以有

mapping | store_id 
--------|--------- 
    a | 1 
    b | 2 
edit-3 | 3 
    c | 4 
edit-5 | 5 

我有下面的代码,但我不知道它用熊猫来充分发挥其潜力

for idx, value in mapping_df["mapping"].iteritems(): 
    if not value: 
     mapping_df["mapping"].iloc[idx] = "edit-{}".format(mapping_df["store_id"].iloc[idx]) 

回答

1

试试这个家伙:

df['mapping'] = df[['mapping', 'store_id']].apply(lambda x: x[0] if x[0] else 'edit-%d' % x[1], axis=1) 
0

如果在映射列中的空白条目NaN而不仅仅是空字符串时,你可以使用combine_first()方法:

df.mapping = df.mapping.combine_first('edit-' + df.store_id.astype(str)) 
+0

是啊,可惜的是他们是空字符串:( – lollerskates

相关问题