Python:从现有列创建新列 [英] Python: create a new column from existing columns

查看:82
本文介绍了Python:从现有列创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据两个列创建一个新列.假设我要创建一个新列z,并且当它不丢失时应为y的值,而当y确实不存在时应为x的值.因此,在这种情况下,我希望z为 [1、8、10、8] .

I am trying to create a new column based on both columns. Say I want to create a new column z, and it should be the value of y when it is not missing and be the value of x when y is indeed missing. So in this case, I expect z to be [1, 8, 10, 8].

   x   y
0  1 NaN
1  2   8
2  4  10
3  8 NaN

推荐答案

新列'z'使用 df从列'y'中获取其值['z'] = df ['y'] .这会遗漏缺少的值,因此请使用 fillna 并使用列'x'填充它们.链接这两个动作:

The new column 'z' get its values from column 'y' using df['z'] = df['y']. This brings over the missing values so fill them in using fillna using column 'x'. Chain these two actions:

>>> df['z'] = df['y'].fillna(df['x'])
>>> df
   x   y   z
0  1 NaN   1
1  2   8   8
2  4  10  10
3  8 NaN   8

这篇关于Python:从现有列创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆