Pandas: Storing A Dataframe Object Inside Another Dataframe I.e. Nested Dataframe
Solution 1:
You are on shaky ground relying on this behavior. pandas does a lot of work trying to infer what you mean or want when passing array like things to its constructors and assignment functions. This is pressing on those boundaries, seemingly intentionally.
It seems that direct assignment via loc
doesn't work. This is a work around I've found. Again, I would not expect this behavior to be robust over pandas versions.
df = pd.DataFrame([[1,2,3],[2,4,6]], columns=list('DEF'))
df_in_df = pd.DataFrame([[11,13,17],[19, 23, 31]], columns=list('XYZ'))
df.loc[df['F'] == 6, 'G'] = np.nan
df.loc[df['F'] == 6, 'G'] = df.loc[df['F'] == 6, ['G']].applymap(lambda x: df_in_df)
df
Solution 2:
Create a Dict first:
x = pd.DataFrame()
y = {'a':[5,4,5],'b':[6,9,7], 'c':[7,3,x]}
# {'a': [5, 4, 5], 'b': [6, 9, 7], 'c': [7, 3, Empty DataFrame# Columns: []# Index: []]}z = pd.DataFrame(y)
# a b c# 0 5 6 7# 1 4 9 3# 2 5 7 Empty DataFrame# Columns: []# Index: []# In [ ]:
(or, convert the DataFrame to dict and try to insert it. There is a lot happening ,when pandas creates objects.. You are torturing pandas. Your use case implies nested dicts, I would use that. )
Solution 3:
First create the column where you want to insert the dictionary. Then convert your dictionary to a string using the repr function. Then insert the string dictionary to your column. If you want to query that string. First select it and then use eval(dict) to convert to dictionary again and use.
Post a Comment for "Pandas: Storing A Dataframe Object Inside Another Dataframe I.e. Nested Dataframe"