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

Tristan Forward picture Tristan Forward · Sep 17, 2014 · Viewed 15.2k times · Source

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.

Answer

YS-L picture YS-L · Sep 17, 2014

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.