Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 304
Tristan Forward Avatar asked Sep 17 '14 15:09

Tristan Forward


People also ask

How do you replace values in a column based on condition in Python?

You can replace all values or selected values in a column of pandas DataFrame based on condition by using DataFrame. loc[] , np. where() and DataFrame. mask() methods.

How do pandas replace values?

Pandas DataFrame replace() Method The replace() method replaces the specified value with another specified value. The replace() method searches the entire DataFrame and replaces every case of the specified value.


2 Answers

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.

like image 101
YS-L Avatar answered Sep 24 '22 08:09

YS-L


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
like image 44
EdChum Avatar answered Sep 20 '22 08:09

EdChum