【问题标题】:pandas: how to convert dictionary to transposed dataframe? [duplicate]pandas:如何将字典转换为转置数据框? [复制]
【发布时间】:2020-04-11 17:55:00
【问题描述】:

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

假设字典的内容是:

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

我尝试通过首先将字典转换为数据帧,然后对数据帧进行转置来解决此问题。

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]

我不知道如何继续。

【问题讨论】:

  • 试试pd.DataFrame(sample_dict)

标签: python pandas dataframe dictionary transpose


【解决方案1】:

简单地说:

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

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 2017-07-16
    • 2020-12-22
    • 1970-01-01
    • 2018-09-22
    • 2018-09-12
    • 1970-01-01
    • 2015-10-20
    相关资源
    最近更新 更多