I have a DataFrame as;
data = pd.DataFrame({
'A': [1,1,1,-1,1,1],
'B':['abc','def','ghi','jkl','mno','pqr']
})
data['A'].replace(1,2)
returns;
0 2
1 2
2 2
3 -1
4 2
5 2
But why doesn't data['A'].replace(1,"pos")
work?
You could also try to use a "map" function.
map_dict = {1: "pos"}
data["test"] = data["A"].map(map_dict)
data
-----------------------
| | A | B | test |
-----------------------
| 0 | 1 | abc | pos |
| 1 | 1 | def | pos |
| 2 | 1 | ghi | pos |
| 3 | -1 | jkl | NaN |
| 4 | 1 | mno | pos |
| 5 | 1 | pqr | pos |
-----------------------
Read more: http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.Series.map.html
You need to convert your column 'A' as type string.
data['A'] = data['A'].astype(str)
and then try
data['A'].replace(str(1),'s')
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