Python 将字典转换为dataframe,其中键作为列名,键的值作为dataframe的列值
将嵌套字典转换为数据帧,其中,字典键作为列名和值对应于数据帧的列值 我是python新手,尝试过几种方法,但都没有成功,请帮助我Python 将字典转换为dataframe,其中键作为列名,键的值作为dataframe的列值,python,dataframe,dictionary,flatten,Python,Dataframe,Dictionary,Flatten,将嵌套字典转换为数据帧,其中,字典键作为列名和值对应于数据帧的列值 我是python新手,尝试过几种方法,但都没有成功,请帮助我 dict= {sheet1:{col1:[a,b,c,d,e],col2:[p,q,r,s,t],col3:[l,m,n,o]},col4:[e,b,w,t,b] sheet2:{col1:[r,w,y,g,r], col2:[q,y,f,w], col3:[w,g,4,2,d]} output: col1 col2 col3 c
dict= {sheet1:{col1:[a,b,c,d,e],col2:[p,q,r,s,t],col3:[l,m,n,o]},col4:[e,b,w,t,b]
sheet2:{col1:[r,w,y,g,r], col2:[q,y,f,w], col3:[w,g,4,2,d]}
output:
col1 col2 col3 col4
a p l e
b q m b
c r n w
d s o t
e t nan b
r q w nan
w y g nan
y f 4 nan
g w 2 nan
r nan d nan
您可以通过从嵌套字典创建多个数据帧,并使用
pd.concat
连接它们来实现这一点。例如:
>>> data = {
... 'sheet1': {'col1': [1, 2, 3, 4], 'col2': [5, 6, 7, 8]},
... 'sheet2': {'col1': [11, 12, 13, 14], 'col2': [15, 16, 17, 18]},
... }
>>> df = pd.concat([pd.DataFrame(d) for d in data.values()], ignore_index=True)
>>> df
col1 col2
0 1 5
1 2 6
2 3 7
3 4 8
4 11 15
5 12 16
6 13 17
7 14 18
您可以从给定的字典创建嵌套的数据帧,然后将它们彼此连接起来 这是一本示例词典
sample_dict= {'sheet1':{'col1':['a','b','c','d','e'],'col2':['p','q','r','s','t'],'col3':['l','m','n','o']},
'sheet2':{'col1':['r','w','y','g','r'], 'col2':['q','y','f','w'], 'col3':['w','g',4,2,'d'], 'col4':['e','b','w','t','b'] }}
然后,您可以为示例dict中的每个键创建一个数据帧列表
最后连接存储在df_列表中的数据帧
我认为你需要学习一些教程:你的dict格式不正确,将dict转储到pandas中是pandas 101。试一试:什么是sheet1、col1、a等?它们是其他地方的字符串还是变量?它们只是字符串
df_list=[]
for key in sample_dict:
df_list.append(pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in sample_dict[key].items()])))
final_df=pd.concat(df_list)