【问题标题】:Fill NaN values using dictionary pandas使用字典 pandas 填充 NaN 值
【发布时间】:2021-12-14 09:38:56
【问题描述】:

我有一个数据框 dfp,其中包含 Brand_IDBrand_Name 列(以及更多列,例如 Product_IDProduct_Name 等)

一些品牌名称是 NaN,因为多个品牌 ID 用逗号分隔(见图)

我想用逗号分隔的实际品牌名称填充这些 NaN。 我有一个参考字典,我可以用它

【问题讨论】:

  • 如果dfp 中的一行有两个Brand_Id,可以在x 中找到怎么办?比如说 ID 8457 和 17831 是 x 中的键,你会怎么做?
  • Brand_ID 是什么类型的数据?字符串?
  • @Riley,是的,Brand_ID 是字符串
  • @BeChillerToo,如果 Brand_ID 中的一行有两个 Brand_ID,则返回 Brand_Name 中的空值。仅当有一个 Brand_ID 时,它才会给出正确的 Brand_Name
  • 哦,好吧,那么我想您可以将字典转换为数据框,然后加入(或根据您的索引合并)您的两个数据框

标签: python pandas dataframe dictionary apply


【解决方案1】:

对于缺少值的行,使用 lambda 函数来拆分值、匹配字典和连接:

df = pd.DataFrame({'Brand_ID': ['11,12,15','10','15,11'],
                   'Brand_Name': [np.nan, 'aaa', np.nan]})


x = {'11': 'ww', '12': 'oup', '15': 'ret'}
m = df['Brand_Name'].isna()
f = lambda y: ','.join(x[z] for z in y.split(',') if z in x)
df.loc[m, 'Brand_Name'] = df.loc[m, 'Brand_ID'].apply(f)

print(df)
   Brand_ID  Brand_Name
0  11,12,15  ww,oup,ret
1        10         aaa
2     15,11      ret,ww

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2015-02-14
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多