在其中一列中将数据帧与dict数据连接起来 [英] Joining data frame with dict data in one of it's columns
本文介绍了在其中一列中将数据帧与dict数据连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据如下:
>>> df = pd.DataFrame({'order_id': ['A', 'B'],
.. 'items': [[{'item': 1, 'color': 'blue' },
... {'item': 2, 'color': 'red' }],
... [{'item': 3, 'color': 'green'},
... {'item': 2, 'color': 'pink' }]]},
... columns= ['order_id', 'items'])
>>> df
order_id items
0 A [{'item': 1, 'color': 'blue'}, {'item': 2, 'color': 'red'}]
1 B [{'item': 3, 'color': 'green'}, {'item': 2, 'color': 'pink'}]
列 items
包含要用作数据框列的字典:
The column items
contains dicts which I want to have as columns of the dataframe:
order_id item color
0 A 1 blue
1 A 2 red
2 B 3 green
3 B 2 pink
ie
到目前为止,我所做的是逐行迭代并在新的数据帧中创建数据:
What I've done so far is to iterate row by row and create the data in a new dataframe:
df2 = pd.DataFrame(columns=['order_id', 'item', 'color'])
for row in df.iterrows():
for items in (row[1]['items']):
df2.loc[-1] =[row[1]['order_id'], items['item'], items['color'] ]
df2.index += 1
给我我需要的结果:
>>> df2
order_id item color
3 A 1 blue
2 A 2 red
1 B 3 green
0 B 2 pink
是否有更有效的方法?也许是因为我要处理大量数据,而无需创建另一个对象并复制所有现有的列?
Is there a more efficient way of doing this? Maybe in place without creating another object and duplicating all the existing columns because I'm dealing with large amounts of data?
推荐答案
重复
,加入
, len
repeat
, join
, len
order_id = df.order_id.values.repeat(df['items'].str.len())
items = pd.DataFrame(np.concatenate(df['items']).tolist())
items.assign(order_id=order_id)
color item order_id
0 blue 1 A
1 red 2 A
2 green 3 B
3 pink 2 B
理解力
Comprehension
pd.DataFrame([{**{'order_id': o}, **i} for o, I in df.values for i in I])
color item order_id
0 blue 1 A
1 red 2 A
2 green 3 B
3 pink 2 B
这篇关于在其中一列中将数据帧与dict数据连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文