【问题标题】:Replace NaN with values from other column based on certain conditions根据特定条件将 NaN 替换为其他列中的值
【发布时间】:2020-04-05 19:59:57
【问题描述】:

我有一个数据集,如下所示,带有多个索引(编号和类型),我想用 l2 中的 R1 值替换 Node1 和 Node2 类型的 l2 列中的 NaN 值,并将 Node3 和 Node4 类型的 NaN 值替换为R2 的 l2 值。 我怎样才能在熊猫中做到这一点?

    name    l1          l2
No. type        
1   Node1   41.656123   NaN
    Node2   95.232711   NaN
    Node3   41.660935   NaN
    Node4   95.144500   NaN
    R1       NaN    0.000144
    R2       NaN    0.000154
2   Node1   41.656142   NaN
    Node2   95.232730   NaN
    Node3   41.660957   NaN
    Node4   95.144525   NaN
    R1       NaN    0.000200
    R2       NaN    0.000232

预期的结果应该是这样的:

    name    l1          l2
No. type        
1   Node1   41.656123   0.000144
    Node2   95.232711   0.000144
    Node3   41.660935   0.000154
    Node4   95.144500   0.000154
    R1       NaN    0.000144
    R2       NaN    0.000154
2   Node1   41.656142   0.000200
    Node2   95.232730   0.000200
    Node3   41.660957   0.000232
    Node4   95.144525   0.000232
    R1       NaN    0.000200
    R2       NaN    0.000232

【问题讨论】:

  • 您能否更具体地说明问题是什么?
  • @Emma 这就是你想要的吗?为了让我们提供帮助,请告诉我们您是否还有其他期望
  • 实际上,我希望条件类似于:如果类型为 Node1 或 Node2,则将这些节点中的 l2 替换为 R1 中的 l2,否则如果类型为 Node3 或 Node4,则将 l2 替换为 R2 中的 l2 .

标签: python pandas


【解决方案1】:

Extract 带有 type 的数据框等于 R1R2replace R1 和 R2 分别带​​有 Node1 和 Node 2

df1=df.query('type == ["R2", "R1"]').reset_index()f#filter Rs to be renamed as Nodes for purposes of joining down the line
df3=df.query('type == ["R2", "R1"]').reset_index()#.set_index('No.')# filter of Rs not to be renamed but to be reappended later
df1.replace(['R1','R2'], ['Node1','Node3'], inplace=True)

Drop l2 因为这里不需要,它有NaNs 和重置索引

df1.drop(columns=['l1'], inplace=True)
df1.set_index(['No.','type'], inplace=True)
df1

使用不等于R1R2type 提取数据帧

df2=df.query('type != ["R2", "R1"]').reset_index()#.set_index('No.')

删除l2 因为这里不需要它,它有NaNs 和重置索引

df2.drop(columns=['l2'], inplace=True)
df2.set_index(['No.','type'], inplace=True)
df2

Merge两个数据框

df4=df1.merge(df2, left_index=True, right_index=True, how='outer').ffill()

回调Rs 的过滤器并设置索引以符合df4

df3.set_index(['No.','type'], inplace=True)
df3

df3 附加到df4 并按索引排序

final=df4.append(df3).sort_index()
final

输出

【讨论】:

  • I want the output to look like: name l1 l2 No. type 1 Node1 41.656123 0.000144 Node2 95.232711 0.000144 Node3 41.660935 0.000154 Node4 95.144500 0.000154 R1 NaN 0.000144 R2 NaN 0.000154 2 Node1 41.656142 0.000200 Node2 95.232730 0.000200 Node3 41.660957 0.000232 节点4 95.144525 0.000232 R1 NaN 0.000200 R2 NaN 0.000232
  • 我无法从评论中看到 clearky,因为没有格式化。您能否编辑问题并插入预期结果以便我们提供帮助?
  • 我已通过添加预期结果来编辑问题。谢谢。
  • 试试修改后的版本。没有给出预期结果的缺点是必须进行插入以修改适合您的答案。这有时会使代码更长。将来尝试预先放置预期的结果。让我知道是否满意,否则我们会提供更多帮助。
  • 谢谢,它起作用了,尽管我必须添加 df3.replace(['R1','R2'], ['Node2','Node4'], inplace=True) 并进行相应修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2018-11-13
  • 2021-08-06
  • 1970-01-01
  • 2019-02-12
  • 2020-01-04
相关资源
最近更新 更多