1

So i'm working on a dataframe which has a key-value pair as its value in columns. Is there a way to make the keys as column name while only keeping the value left in the column.

Currently i have something like this:

    >0                          1                       2   
    >{'1536235175000': 26307.9} {'1536235176000': 0}    {'1536236701000': 2630} 
    >{'1536239919000': 1028127} {'1536239921000': 0}    NaN 
    >{'1536242709000': 2629.6}  {'1536242711000': 0}    NaN 
nandi1596
  • 59
  • 7
  • So for you example, are you looking to end up with 7 columns and one data row? – pakpe Jan 12 '21 at 03:26
  • no, i am looking for the keys(like '1536235175000') as columns and whatever value is with it should be the column value. So there will be more than one data row depending on how many times i get the column(key) – nandi1596 Jan 12 '21 at 03:31

2 Answers2

1

If you want to keep the row index, you can agg every row as as list and explode them.

obj = df.apply(lambda x: list(x), axis=1).explode().dropna()
dfn = pd.DataFrame(obj.tolist(), index=obj.index)
dfn.stack().unstack()
#        1536235175000  1536235176000  1536236701000  1536239919000  \
# 0            26307.9            0.0         2630.0            NaN   
# 1                NaN            NaN            NaN      1028127.0   
# 2                NaN            NaN            NaN            NaN   

#        1536239921000  1536242709000  1536242711000  
# 0                NaN            NaN            NaN  
# 1                0.0            NaN            NaN  
# 2                NaN         2629.6            0.0
Ferris
  • 5,325
  • 1
  • 14
  • 23
0

Check with concat

pd.concat([pd.Series(df[x].tolist()) for x in df.columns], keys=df.columns, axis=1)
BENY
  • 317,841
  • 20
  • 164
  • 234