Python 熊猫:如何将字典转换为转置数据帧?
我有一个列表字典(等长),我想将其转换为一个数据帧,以便字典中的每个键表示数据帧中的一列(或系列),并且对应于每个键的值列表转换为列中的单个记录 假设字典的内容是:Python 熊猫:如何将字典转换为转置数据帧?,python,pandas,dataframe,dictionary,transpose,Python,Pandas,Dataframe,Dictionary,Transpose,我有一个列表字典(等长),我想将其转换为一个数据帧,以便字典中的每个键表示数据帧中的一列(或系列),并且对应于每个键的值列表转换为列中的单个记录 假设字典的内容是: sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']} 我希望dataframe的内容是: col1 col2 --- --- 0 abc 1a2b 1 de
sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']}
我希望dataframe的内容是:
col1 col2
--- ---
0 abc 1a2b
1 def pqr lmno
2 w xyz qr st
我尝试通过首先将字典转换为数据帧,然后对数据帧进行转置来解决这个问题
import pandas as pd
sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']}
sample_df = pd.DataFrame(list(sample_dict.items()))
sample_df.transpose()
这将提供以下输出:
0 1
--- ---
0 col2 col1
1 [1a2b, lmno, qr st] [abc, def pqr, w xyz]
我不知道如何进一步进行。简单地说:
import pandas as pd
sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']}
sample_df = pd.DataFrame(sample_dict)
print (sample_df)
输出:
col1 col2
0 abc 1a2b
1 def pqr lmno
2 w xyz qr st
尝试使用pd.DataFrame(示例dict)