How do I set tuple value to pandas dataframe?

You can wrap the tuples in a list:

import pandas as pd
pd_tmp = pd.DataFrame(np.random.rand(3,3))
pd_tmp["new_column"] = [("a",2)] * len(pd_tmp)

pd_tmp
#          0           1           2    new_column
#0  0.835350    0.338516    0.914184    (a, 2)
#1  0.007327    0.418952    0.741958    (a, 2)
#2  0.758607    0.464525    0.400847    (a, 2)

I was looking for something similar, but in my case I wanted the tuple to be a combination of the existing columns, not just a fixed value. I found the solution below, which I share hoping it will be useful to others, like me.

In [24]: df
Out[24]:
      A     B
0     1     2
1    11    22
2   111   222
3  1111  2222

In [25]: df['D'] = df[['A','B']].apply(tuple, axis=1)

In [26]: df
Out[26]:
      A     B             D
0     1     2        (1, 2)
1    11    22      (11, 22)
2   111   222    (111, 222)
3  1111  2222  (1111, 2222)

You can use apply with a lambda that returns the tuple

pd_tmp.assign(newc_olumn=pd_tmp.apply(lambda x: ('a', 2), 1))

          0         1         2 newc_olumn
0  0.373564  0.806956  0.106911     (a, 2)
1  0.332508  0.711735  0.230347     (a, 2)
2  0.516232  0.343266  0.813759     (a, 2)

Tags:

Python

Pandas