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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With