繁体   English   中英

python pandas - 用字符串替换数字

[英]python pandas - replace number with string

我有一个DataFrame;

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

data['A'].replace(1,2)

回报;

0    2
1    2
2    2
3   -1
4    2
5    2

但为什么data['A'].replace(1,"pos")工作?

您也可以尝试使用“地图”功能。

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

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

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

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

然后试试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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