10

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?

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

Comments

10

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.