【发布时间】:2017-07-11 21:02:06
【问题描述】:
我目前有一个包含两个元素的元组列表,一个字符串和三个键值对的字典。
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
想要将原始数据结构转换为表格格式的最佳方式吗?
【问题讨论】:
标签: python pandas dictionary dataframe tuples