Add a tuple to a specific cell of a pandas dataframe Add a tuple to a specific cell of a pandas dataframe pandas pandas

Add a tuple to a specific cell of a pandas dataframe


You can use set_value:

tempDF.set_value(i,'newTuple', anyOldTuple)

Also make sure that the column is not a float column, for example:

tempDF['newTuple'] = 's' # or set the dtype

otherwise you will get an error.


set_value is deprecated.

you can just use .at[] or iat[]

e.g. some_df.at[ idx, col_name] = any_tuple


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.