简体   繁体   中英

python pandas - replace number with string

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM