Pandas:如何将字典转换为转置的数据框?

3

我有一个列表的字典(长度相等),我想将其转换为数据框,以便字典中的每个键代表数据框中的一列(或系列),与每个键对应的值列表被转换为该列中的单独记录。

假设字典的内容如下:

sample_dict = {'col1':['abc','def pqr','w xyz'],'col2':['1a2b','lmno','qr st']}

我希望数据帧的内容为:
    col1        col2
    ---         ---
0   abc         1a2b
1   def pqr     lmno
2   w xyz       qr st

我曾尝试将该字典转换为数据框(dataframe),然后对数据框进行转置以解决此问题。

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]

我不确定该如何进一步进行。


1
尝试使用 pd.DataFrame(sample_dict) - Sociopath
1个回答

2

简单来说:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接