繁体   English   中英

根据特定条件将 NaN 替换为其他列中的值

[英]Replace NaN with values from other column based on certain conditions

我有一个带有多个索引(编号和类型)的数据集,如下所示,我想用来自 l2 的 R1 值替换 Node1 和 Node2 类型的列 l2 中的 NaN 值,并用 l2 值替换 Node3 和 Node4 类型的 NaN 值R2。 如何在 pandas 中执行此操作?

    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

提取typeR1R2的 dataframe 并将 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)

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

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

提取 dataframe type不等于R1R2

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

合并两个数据框

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

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

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

Append df3df4并按索引排序

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

Output

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM