2

I'm using dataframe. How to split dict list to many columns?

This is for a junior dataprocessor. In the past, I've tried on many ways.

import pandas as pd
l = [{'a':1,'b':2},{'a':3,'b':4}]
data = [{'key1':'x','key2':'y','value':l}]
df = pd.DataFrame(data)
data1 = {'key1':['x','x'],'key2':['y','y'],'a':[1,3],'b':[2,4]}
df1 = pd.DataFrame(data1)

df1 is what I need.

Serenity
  • 35,289
  • 20
  • 120
  • 115
Todd
  • 55
  • 1
  • 5

1 Answers1

2

comprehension

d1 = df.drop('value', axis=1)
co = d1.columns
d2 = df.value

pd.DataFrame([
    {**dict(zip(co, tup)), **d}
    for tup, D in zip(zip(*map(d1.get, d1)), d2)
    for d in D
])

   a  b key1 key2
0  1  2    x    y
1  3  4    x    y

Explode

See post on explode
This is a tad different but close

idx = df.index.repeat(df.value.str.len())
val = np.concatenate(df.value).tolist()
d0 = pd.DataFrame(val)
df.drop('value', axis=1).loc[idx].reset_index(drop=True).join(d0)

   a  b key1 key2
0  1  2    x    y
1  3  4    x    y
piRSquared
  • 285,575
  • 57
  • 475
  • 624