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

☆樱花仙子☆ 提交于 2019-12-30 03:05:06

问题


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"

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


回答1:


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 ix or loc to avoid setting values on a copied slice.




回答2:


Use isin and loc to set the value:

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:

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


来源:https://stackoverflow.com/questions/25895154/python-pandas-if-value-in-column-b-equals-x-y-z-replace-column-a-with-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!