python - pandas:如何将字典转换为转置数据框?

标签 python pandas dataframe dictionary transpose

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

假设字典的内容是:

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]

我不知道如何进一步进行。

最佳答案

简单地说:

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

关于python - pandas:如何将字典转换为转置数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59404567/

相关文章:

python - CNN OCR 机器可读区

python - 从 DateTimeIndex 中截断毫秒

python - 当其他列满足某些条件时,如何使用 fillna() 估算列中的值

r - 将唯一行添加到数据框(与相交相反)

python - pandas DataFrame - 查找偏移列之间的最大值

python - 如何使用已计算的 TFIDF 分数计算余弦相似度

python - Matplotlib Contour Clabel 位置

python - 根据长度排序python列表,然后根据内容排序

python - 如何使用Python打开大文件(9GB)?

python - 使用 str.replace() 从 Pandas 数据框中的字符串中删除第 n 个字符