本文介绍了从一列获取多本词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有少量数据
ID Name Detail
1 Sara [{"Personal":{"ID":"001","Name":"Sara","Type":"01","TypeName":"Book"},"Order":[{"ID":"0001","Date":"20200222","ProductID":"C0123","ProductName":"ABC", "Price":"4"}]}]
2 Sara [{"Personal":{"ID":"001","Name":"Sara","Type":"02","TypeName":"Food"},"Order":[{"ID":"0004","Date":"20200222","ProductID":"D0123","ProductName":"Small beef", "Price":"15"}]}]
3 Frank [{"Personal":{"ID":"002","Name":"Frank","Type":"02","TypeName":"Food"},"Order":[{"ID":"0008","Date":"20200228","ProductID":"D0288","ProductName":"Salmon", "Price":"24"}]}]
如何进入详细信息列
ID Name Personal_ID Personal_Name Personal_Type Personal_TypeName Personal_Order_ID Personal_Order_Date Personal_Order_ProductID Personal_Order_ProductName Personal_Order_Price
1 Sara 001 Sara 01 Book 0001 20200222 C0123 ABC 4
2 Sara 001 Sara 02 Food 0004 20200222 D0123 Small beef 15
3 Frank 002 Frank 02 Food 0008 20200228 D0288 Salmon 24
推荐答案
使用,提取与内部键相关联的值 Detail
列中的字典,然后使用 apply(pd.Series)
将此字典转换为数据框,然后使用添加列标签的前缀。然后使用沿 axis = 1
来连接个人
和一起订购
数据框:
Use, Series.str.get
to extract the values associated with the keys inside the dictionary in the Detail
column then using apply(pd.Series)
transform this dictionary into dataframe, then use DataFrame.add_prefix
to add the prefix to the column labels. Then use pd.concat
along axis=1
to concat the personal
and order
dataframe together:
# step 1
personal = df['Detail'].str[0].str.get('Personal').apply(pd.Series).add_prefix('Personal_')
# step 2
order = df['Detail'].str[0].str.get('Order').str[0].apply(pd.Series).add_prefix('Personal_Order_')
# step 3
result = pd.concat([df[['ID', "Name"]], personal, order], axis=1)
步骤:
Steps:
# step 1: personal
Personal_ID Personal_Name Personal_Type Personal_TypeName
0 001 Sara 01 Book
1 001 Sara 02 Food
2 002 Frank 02 Food
# step 2: order
Personal_Order_ID Personal_Order_Date Personal_Order_ProductID Personal_Order_ProductName Personal_Order_Price
0 0001 20200222 C0123 ABC 4
1 0004 20200222 D0123 Small beef 15
2 0008 20200228 D0288 Salmon 24
# step 3: result
ID Name Personal_ID Personal_Name ... Personal_Order_Date Personal_Order_ProductID Personal_Order_ProductName Personal_Order_Price
0 1 Sara 001 Sara ... 20200222 C0123 ABC 4
1 2 Sara 001 Sara ... 20200222 D0123 Small beef 15
2 3 Frank 002 Frank ... 20200228 D0288 Salmon 24
这篇关于从一列获取多本词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!