Add A Tuple To A Specific Cell Of A Pandas Dataframe
Just when I thought I was getting the hang of Python and Pandas, another seemingly simple issue crops up. I want to add tuples to specific cells of a pandas dataframe. These tuples
Solution 1:
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.
Solution 2:
set_value is deprecated.
you can just use .at[] or iat[]
e.g. some_df.at[ idx, col_name] = any_tuple
Solution 3:
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:
dfinitializedas:
abc001213452678dfcontainingtuple:
abc00 (1, 2) 213452678
Code:
import numpy as np
import pandas as pd
df = 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.
Post a Comment for "Add A Tuple To A Specific Cell Of A Pandas Dataframe"