Python Pandas 如果 B 列中的值 = 等于 [X, Y, Z] 将 A 列替换为“T”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25895154/
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-13 22:28:39  来源:igfitidea点击:

Python Pandas If value in column B = equals [X, Y, Z] replace column A with "T"

pythonpandascomparisonmultiple-columns

提问by Tristan Forward

Say I have this array:

说我有这个数组:

A, B
1, G
2, X
3, F
4, Z
5, I

If column B equals [X, Y or Z] replace column A with value "T"

如果 B 列等于 [X、Y 或 Z],则将 A 列替换为值“T”

I've found how to change values within the same column but not across, any help would be most appreciated.

我已经找到了如何在同一列中而不是跨列中更改值,任何帮助将不胜感激。

回答by YS-L

You can try this:

你可以试试这个:

import pandas as pd
df = pd.DataFrame({
        'A': [1, 2, 3, 4, 5],
        'B': ['G', 'X', 'F', 'Z', 'I']
     })
df.ix[df.B.isin(['X','Y','Z']), 'A'] = 'T'
print df

Output:

输出:

   A  B
0  1  G
1  T  X
2  3  F
3  T  Z
4  5  I

Remember to use ixor locto avoid setting values on a copied slice.

请记住使用ixloc避免在复制的切片上设置值。

回答by EdChum

Use isinand locto set the value:

使用isinloc设置值:

In [138]:

df.loc[df.B.isin(['X','Y','Z']),'A']='T'
df
Out[138]:
   A  B
0  1  G
1  T  X
2  3  F
3  T  Z
4  5  I

You can also use np.where:

您还可以使用np.where

In [140]:

df['A'] = np.where(df.B.isin(['X','Y','Z']),'T', df['A'])
df
Out[140]:
   A  B
0  1  G
1  T  X
2  3  F
3  T  Z
4  5  I