如果条件满足,pandas 创建一列等于另一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33676143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:13:13  来源:igfitidea点击:

pandas create one column equal to another if condition is satisfied

pythonif-statementpandas

提问by As3adTintin

I have two columns as below:

我有两列如下:

id, colA, colB
0, a, 13
1, a, 52
2, b, 16
3, a, 34
4, b, 946
etc...

I am trying to create a third column, colC, that is colBif colA == a, otherwise 0.

我正在尝试创建第三列colC,即colBif colA == a, else 0

This is what I was thinking, but it does not work:

这是我的想法,但它不起作用:

data[data['colA']=='a']['colC'] = data[data['colA']=='a']['colB']

I was also thinking about using np.where(), but I don't think that would work here.

我也在考虑使用np.where(),但我认为这在这里行不通。

Any thoughts?

有什么想法吗?

回答by EdChum

Use locwith a mask to assign:

loc与掩码一起使用以分配:

In [300]:
df.loc[df['colA'] == 'a', 'colC'] = df['colB']
df['colC'] = df['colC'].fillna(0)
df

Out[300]:
   id colA  colB  colC
0   0    a    13    13
1   1    a    52    52
2   2    b    16     0
3   3    a    34    34
4   4    b   946     0

EDIT

编辑

or use np.where:

或使用np.where

In [296]:
df['colC'] = np.where(df['colA'] == 'a', df['colC'],0)
df

Out[296]:
   id colA  colB  colC
0   0    a    13    13
1   1    a    52    52
2   2    b    16     0
3   3    a    34    34
4   4    b   946     0

回答by vmg

df['colC'] = df[df['colA'] == 'a']['colB'] 

should result in exactly what you want, afaik.

应该会产生你想要的结果,afaik。

Then replace the NaN's with zeroes with df.fillna(inplace=True)

然后用零替换 NaN df.fillna(inplace=True)