繁体   English   中英

在熊猫中使用 if 条件组合两列

[英]Combine two columns with if condition in pandas

我有两列数据在某些条目上重叠(并且在它们重叠时几乎相似)。

df = pd.DataFrame(
                  {'x':[2.1,3.1,5.4,1.9,np.nan,4.3,np.nan,np.nan,np.nan],
                   'y':[np.nan,np.nan,5.3,1.9,3.2,4.2,9.1,7.8,4.1]
                  }
                 )

我希望结果是一列“xy”,其中包含 x 和 y 的平均值,当它们都具有值时,x 或 y 中只有一个具有如下值:

df['xy']=[2.1,3.1,5.35,1.9,3.2,4.25,9.1,7.8,4.1]

干得好:

解决方案

df['xy'] = df[['x','y']].mean(axis=1)

输出

print(df.to_string())

     x    y    xy
0  2.1  NaN  2.10
1  3.1  NaN  3.10
2  5.4  5.3  5.35
3  1.9  1.9  1.90
4  NaN  3.2  3.20
5  4.3  4.2  4.25
6  NaN  9.1  9.10
7  NaN  7.8  7.80
8  NaN  4.1  4.10

暂无
暂无

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

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