Python数据框包含字典列表,需要使用字典项创建新的数据框 [英] Python Dataframe contains a list of dictionaries, need to create new dataframe with dictionary items
问题描述
我有一个Python数据框,其中包含字典列表(针对某些行):
I have a Python dataframe that contains a list of dictionaries (for certain rows):
In[1]:
cards_df.head()
Out[1]:
card_id labels
0 'cid_1' []
1 'cid_2' []
3 'cid_3' [{'id': 'lid_a', 'name': 'lname_a'}, {'id': 'lid_b', 'name': 'lname_b'}]
4 'cid_4' [{'id': 'lid_c', 'name': 'lname_c'}]
我会就像创建一个新的数据框,将字典项列表扩展到单独的行中:
I would like to create a new dataframe that expands the list of dictionary items into separate rows:
card_id label_id label_name
0 cid_3 lid_a lname_a
1 cid_3 lid_b lname_b
2 cid_4 lid_c lname_c
推荐答案
使用 pd.Series.str.len
生成适当的值,以传递给 np.repeat
。这反过来又用于重复 df.card_id.values
的值,并构成新数据框的第一列。
Use pd.Series.str.len
to produce the appropriate values to pass to np.repeat
. This in turn is used to repeat the values of df.card_id.values
and make the first column of our new dataframe.
然后在 df ['labels']上使用
pd.Series.sum
code>将所有列表连接成一个列表。现在,此新列表非常适合传递给 pd.DataFrame
构造函数。剩下的就是在每个列名称前添加一个字符串,然后加入我们上面创建的列。
Then use pd.Series.sum
on df['labels']
to concatenate all lists into a single list. This new list is now perfect for passing to the pd.DataFrame
constructor. All that's left is to prepend a string to each column name and join to the column we created above.
pd.DataFrame(dict(
card_id=df.card_id.values.repeat(df['labels'].str.len()),
)).join(pd.DataFrame(df['labels'].sum()).add_prefix('label_'))
card_id label_id label_name
0 cid_3 lid_a lname_a
1 cid_3 lid_b lname_b
2 cid_4 lid_c lname_c
设置
df = pd.DataFrame(dict(
card_id=['cid_1', 'cid_2', 'cid_3', 'cid_4'],
labels=[
[],
[],
[
{'id': 'lid_a', 'name': 'lname_a'},
{'id': 'lid_b', 'name': 'lname_b'}
],
[{'id': 'lid_c', 'name': 'lname_c'}],
]
))
这篇关于Python数据框包含字典列表,需要使用字典项创建新的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!