【问题标题】:Replacing NaN Values with another dataframe with pandas python用 pandas python 用另一个数据框替换 NaN 值
【发布时间】:2017-12-03 17:15:22
【问题描述】:

在从另一个具有不同索引长度的数据帧中替换一个数据帧中 NaN 值的一列到期日期时,我有点卡住了。

样本数据df1:

    SOH     Price     Value  Expiry  Comments  
0    1P     10.49     10.49     NaN       NaN  
1   220      7.55     16.61     NaN       NaN  

用 df2 替换过期列:

    SOH     Price     Value    Expiry  Comments  
1    1P      6.22      6.22     NaN       NaN  
2    61     17.65     10.77     NaN       NaN  
3    1P     11.99     11.99     NaN       NaN  
4    2P     54.45    108.90     NaN       NaN  
5    1P     10.49     10.49     May-17       NaN  
6   220      7.55     16.61     June-18       NaN 

所以新的数据框可能有不同的顺序和索引,但列保持不变。

我希望 df1 输出为:
SOH 价格 价值 到期评论
0 1P 10.49 10.49 May-17 NaN
1 220 7.55 16.61 June18 NaN

我试过了:

  • df1.fillna(df2),
  • df1.update(df2)
  • df1.loc[df1['Expiry'].isnull(),'Expiry'] = df1['Expiry'].map(df2.Expiry)
  • 带有 3 个参数的正向循环,
  • 合并
  • 内连接

但还没有运气:(任何帮助将不胜感激!

【问题讨论】:

  • 你是基于SOH列替换吗?
  • 不,我需要价格和价值来匹配,以防有其他 SOH 看起来相同

标签: python-3.x pandas


【解决方案1】:

join['SOH', 'Price', 'Value'] 然后fillna

cols = ['SOH', 'Price', 'Value']
d2 = df2.set_index(cols).Expiry.dropna()
df1.fillna(df1.drop('Expiry', 1).join(d2, on=cols))

   SOH  Price  Value   Expiry Comments
0   1P  10.49  10.49   May-17      NaN
1  220   7.55  16.61  June-18      NaN

【讨论】:

  • 感谢您的快速响应,但奇怪的是“d2 = df2.set_index(cols).Expiry.dropna()”给了我 AttributeError: 'DataFrame' object has no attribute 'Expiry'
  • 那么你的列名不是你想象的那样
  • 它与 .set_index(cols) 一起出现,我的 print(d2) 变为:Empty DataFrame Columns: [] Index: [105, 22.92, 40.11, nan, nan, etc],任何指向什么的指针我做错了吗?看起来它只是将所有内容都设置到索引中,列中没有值
  • 你在使用cols = ['SOH', 'Price', 'Value']吗? print(df2.columns)` 说什么?
  • 是的,我按照你的建议做了,print(d2.columns) 给出:Index(['SOH', 'Price', 'Value', 'Expiry', 'Comments'], dtype=' object'),并且 d1 列也给出相同的值
猜你喜欢
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2022-10-05
  • 1970-01-01
  • 2021-11-24
  • 2020-11-07
相关资源
最近更新 更多