python pandas - 用字符串替换数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20093474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:22:10  来源:igfitidea点击:

python pandas - replace number with string

pythonpandas

提问by richie

I have a DataFrame as;

我有一个 DataFrame 作为;

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?

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

回答by Sviterok

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

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

回答by Kathirmani Sukumar

You need to convert your column 'A' as type string.

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

data['A'] = data['A'].astype(str) 

and then try

然后尝试

data['A'].replace(str(1),'s')