python pandas - 用字符串替换数字

ric*_*hie 2 python pandas

我有一个DataFrame;

data = pd.DataFrame({
       'A': [1,1,1,-1,1,1],
       'B':['abc','def','ghi','jkl','mno','pqr']
       })

data['A'].replace(1,2)
Run Code Online (Sandbox Code Playgroud)

回报;

0    2
1    2
2    2
3   -1
4    2
5    2
Run Code Online (Sandbox Code Playgroud)

但为什么不起作用data['A'].replace(1,"pos")

Kat*_*mar 8

您需要将列 'A' 转换为字符串类型。

data['A'] = data['A'].astype(str) 
Run Code Online (Sandbox Code Playgroud)

然后尝试

data['A'].replace(str(1),'s')
Run Code Online (Sandbox Code Playgroud)


Svi*_*rok 7

您也可以尝试使用"地图"功能.

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  |
-----------------------
Run Code Online (Sandbox Code Playgroud)

阅读更多:http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.Series.map.html