2
df = pd.DataFrame({'Tissues':['a1','x2','y3','b','c1','v2','w3'], 'M':[1,2,'a',4,'b','a',7]})
df.set_index('Tissues')

The dataframe looks like:

         M
Tissues   
a1       1
x2       2
y3       a
b        4
c1       b
v2       a
w3       7

How can I replace all as in column M with say a specific value, 2 and all bs to 3?

I tried:

replace_values = {'a':2, 'b':3}
df['M'] = df['M'].map(replace_values)

, but that changed other values not in the keys in replace_values to NaN:

  Tissues    M
0      a1  NaN
1      x2  NaN
2      y3  2.0
3       b  NaN
4      c1  3.0
5      v2  2.0
6      w3  NaN

I see that I can do

df.loc[(df['M'] == 'a')] = 2

but can I do this efficiently for a, b and so on, instead of one by one?

1
  • 2
    Your own solution was perfectly fine, just missed fillna, replace last line with: df['M'] = df['M'].map(replace_values).fillna(df['M']) Commented Jan 7, 2020 at 15:49

3 Answers 3

6

Use df.replace:

df = pd.DataFrame({'Tissues':['a1','x2','y3','b','c1','v2','w3'], 'M':[1,2,'a',4,'b','a',7]})
df.set_index('Tissues')

replace_values = {'a':2, 'b':3}

df['M'] = df['M'].replace(replace_values)

Output:

>>> df
  Tissues  M
0      a1  1
1      x2  2
2      y3  2
3       b  4
4      c1  3
5      v2  2
6      w3  7
Sign up to request clarification or add additional context in comments.

Comments

4

Fix your code by add fillna

df['M'] = df['M'].map(replace_values).fillna(df.M)
df
  Tissues    M
0      a1  1.0
1      x2  2.0
2      y3  2.0
3       b  4.0
4      c1  3.0
5      v2  2.0
6      w3  7.0

Comments

2

Use df.replace

replace_values = {'a':2, 'b':3}
df = df.replace({"M": replace_values})

Results:

Tissues  M
0      a1  1
1      x2  2
2      y3  a
3       b  4
4      c1  b
5      v2  a
6      w3  7

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.