Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas - replace number with string

Tags:

python

pandas

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?

like image 953
richie Avatar asked Nov 20 '13 10:11

richie


2 Answers

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

like image 109
Sviterok Avatar answered Oct 12 '22 06:10

Sviterok


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')
like image 28
Kathirmani Sukumar Avatar answered Oct 12 '22 07:10

Kathirmani Sukumar