如何将元组中的字典列表转换为表格数据/ pandas DataFrame?

时间:2017-02-22 01:04:53

标签: python pandas dictionary dataframe tuples

我目前有一个包含两个元素的元组列表,一个字符串和三个键值对的字典。

list1 = [("string1", {"a": 1, "b": 2, "c": 3}), 
         ("string2", {"a": 11, "b": 21, "c": 31}), ...]

这是一团糟。我想把这是DataFrame格式。预期的格式应该是

strings    a    b    c
string1    1    2    3
string2    11   21   31

如何将其解压缩为类似DataFrame的格式?对于元组中的第一个元素,我怀疑我们会按如下方式解压缩字符串:

import pandas as pd
for i in list1:
    df = pd.DataFrame()
    df["strings"] = pd.DataFrame([list1[i][0]]) # create the `strings` column
    # place the 2nd element of the tuple in a DataFrame, and then merge with `df`
    df = df.merge(df, pd.DataFrame(list1[0][i]))   

这当然不起作用。

TypeError: list indices must be integers, not tuple

想要将原始数据结构变成表格格式的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

list1 = [("string1", {"a": 1, "b": 2, "c": 3}), 
         ("string2", {"a": 11, "b": 21, "c": 31})]

df = pd.DataFrame([row[1] for row in list1]) # create df from list of dicts
df["strings"] = [row[0] for row in list1] # add the string column 

如果需要,您可以添加:

df.set_index("strings", inplace=True)

答案 1 :(得分:0)

另一个选项是,您可以将列表转换为字典,然后使用pd.DataFrame.from_dict

pd.DataFrame.from_dict(dict(list1), orient="index").rename_axis("strings").reset_index()

#    strings     b   a   c
#0   string1     2   1   3
#1   string2    21  11  31
相关问题