来自带有列表的字典的 Pandas DataFrame [英] Pandas DataFrame from Dictionary with Lists
问题描述
我有一个 API,可以将单行数据作为 Python 字典返回.大多数键只有一个值,但有些键的值是列表(甚至是列表列表或字典列表).
I have an API that returns a single row of data as a Python dictionary. Most of the keys have a single value, but some of the keys have values that are lists (or even lists-of-lists or lists-of-dictionaries).
当我将字典放入 pd.DataFrame 以尝试将其转换为 Pandas DataFrame 时,它抛出一个数组必须具有相同长度";错误.这是因为它无法处理具有多个值的键(即具有列表值的键).
When I throw the dictionary into pd.DataFrame to try to convert it to a pandas DataFrame, it throws a "Arrays must be the same length" error. This is because it cannot process the keys which have multiple values (i.e. the keys which have values of lists).
如何让 Pandas 将列表视为单个值"?
How do I get pandas to treat the lists as 'single values'?
作为一个假设的例子:
data = { 'building': 'White House', 'DC?': True,
'occupants': ['Barack', 'Michelle', 'Sasha', 'Malia'] }
我想把它变成这样的 DataFrame:
I want to turn it into a DataFrame like this:
ix building DC? occupants
0 'White House' True ['Barack', 'Michelle', 'Sasha', 'Malia']
推荐答案
如果你传递一个列表(行),这有效:
This works if you pass a list (of rows):
In [11]: pd.DataFrame(data)
Out[11]:
DC? building occupants
0 True White House Barack
1 True White House Michelle
2 True White House Sasha
3 True White House Malia
In [12]: pd.DataFrame([data])
Out[12]:
DC? building occupants
0 True White House [Barack, Michelle, Sasha, Malia]
这篇关于来自带有列表的字典的 Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!