Replace a cell's value in pandas to a tuple

Viewed 869

This might be a simple question but I tried searching for the answer and I can't seem to find it. I have a pandas dataframe and I want to change the value of some cells to a tuple.

So if I have this:

 Col0    Col1     Col2
   3      a        6
   7      b        8

I would like to change all the "a" values to a tuple:

Col0      Col1     Col2
3         (4,5)      6
7          b         8

I tried doing this:

df.loc[df["Col1"] == "a"] = (4,5,)

but it obviously didn't work. I don't know how I can do this.

How can I do this?

2 Answers

Maybe something like this?

import pandas as pd
df = pd.DataFrame(data = {'Col0': [3,7], 'Col1': ['a', 'b'], 'Col2': [6, 8]})
df.set_value(0, 'Col1', (4, 5))

Or, if you don't know where 'a' is (and in case we have more than one 'a0 per column, you can do that with a loop:

import pandas as pd
import numpy as np

df = pd.DataFrame(data = {'Col0': [3,7], 'Col1': ['a', 'b'], 'Col2': [6, 8]})
# find the position of a in 'Col1'
where_a = np.where(df['Col1'] == 'a')[0]

# replace a with tuple (4, 5)
for x in where_a:
    df.set_value(x, 'Col1', (4, 5))

   Col0    Col1  Col2
0     3  (4, 5)     6
1     7       b     8

Let's try boolean indexing with loc to update the values in the cells in Col1 which contains a:

m = df['Col1'].eq('a')
df.loc[m, 'Col1'] = pd.Series([(4, 5)]*m.sum(), index=m[m].index)

Alternatively you can try .reindex with fill_value parameter set to tuple (4, 5):

m = df['Col1'].eq('a')
df['Col1'] = df.loc[~m, 'Col1'].reindex(m.index, fill_value=(4, 5))

   Col0    Col1  Col2
0     3  (4, 5)     6
1     7       b     8
Related