Add a tuple to a specific cell of a pandas dataframe
As J.Melody pointed out, .at[]
and .iat[]
can be used to assign a tuple to a cell, if the dtype of the column is object
.
Minimal example:
df initialized as: a b c0 0 1 21 3 4 52 6 7 8df containing tuple: a b c0 0 (1, 2) 21 3 4 52 6 7 8
Code:
import numpy as npimport pandas as pddf = pd.DataFrame(np.arange(9).reshape((3,3)), columns=list('abc'), dtype=object)print('df initialized as:', df, sep='\n')df.at[0,'b'] = (1,2)print()print('df containing tuple:', df, sep='\n')
Note:
If you skip , dtype=object
, you end up with
ValueError: setting an array element with a sequence.