将词典列表转换为Pandas数据框架

2024-04-24 04:02:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的字典列表:

[{'points': 50, 'time': '5:00', 'year': 2010}, 
{'points': 25, 'time': '6:00', 'month': "february"}, 
{'points':90, 'time': '9:00', 'month': 'january'}, 
{'points_h1':20, 'month': 'june'}]

我想把它变成熊猫,就像这样:

      month  points  points_h1  time  year
0       NaN      50        NaN  5:00  2010
1  february      25        NaN  6:00   NaN
2   january      90        NaN  9:00   NaN
3      june     NaN         20   NaN   NaN

注意:列的顺序无关紧要。

如何将字典列表转换为如上所示的pandas数据框?


Tags: 数据pandas列表字典time顺序nanh1
3条回答

How do I convert a list of dictionaries to a pandas DataFrame?

其他的答案是正确的,但没有多少解释这些方法的优点和局限性。这篇文章的目的是展示这些方法在不同情况下的例子,讨论何时使用(何时不使用),并提出替代方案。


^{}^{}^{}

根据数据的结构和格式,有些情况下,三种方法都可以工作,有些方法工作得更好,有些根本不工作。

举一个非常做作的例子。

np.random.seed(0)
data = pd.DataFrame(
    np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')

print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]

此列表由“记录”组成,每个键都存在。这是你可能遇到的最简单的情况。

# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

字典方向上的单词:orient='index'/'columns'

在继续之前,重要的是区分不同类型的字典方向,并支持熊猫。有两种主要类型:“列”和“索引”。

orient='columns'
具有“columns”方向的字典的键将与等效数据帧中的列相对应。

例如,上面的data位于“列”方向。

data_c = [
 {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]

pd.DataFrame.from_dict(data_c, orient='columns')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

注意:如果您使用的是pd.DataFrame.from_records,则方向假定为“列”(您不能另外指定),并且字典将相应地加载。

orient='index'
使用这个方向,键被假定与索引值相对应。这种数据最适合于pd.DataFrame.from_dict

data_i ={
 0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}

pd.DataFrame.from_dict(data_i, orient='index')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

本案不在手术室考虑,但仍需了解。

设置自定义索引

如果需要生成的数据帧上的自定义索引,可以使用index=...参数对其进行设置。

pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])

   A  B  C  D
a  5  0  3  3
b  7  9  3  5
c  2  4  7  6

这不受pd.DataFrame.from_dict支持。

处理丢失的键/列

当处理缺少键/列值的字典时,所有方法都是开箱即用的。例如

data2 = [
     {'A': 5, 'C': 3, 'D': 3},
     {'A': 7, 'B': 9, 'F': 5},
     {'B': 4, 'C': 7, 'E': 6}]

# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)

     A    B    C    D    E    F
0  5.0  NaN  3.0  3.0  NaN  NaN
1  7.0  9.0  NaN  NaN  NaN  5.0
2  NaN  4.0  7.0  NaN  6.0  NaN

读取列的子集

“如果我不想在每一个专栏里都读呢?”?您可以使用columns=...参数轻松地指定它。

例如,从上面data2的示例字典中,如果您只想读取列“A”、“D”和“F”,可以通过传递列表来执行此操作:

pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])

     A    D    F
0  5.0  3.0  NaN
1  7.0  NaN  5.0
2  NaN  NaN  NaN

具有默认方向“列”的pd.DataFrame.from_dict不支持此操作。

pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])

ValueError: cannot use columns parameter with orient='columns'

读取行的子集

这些方法中的任何一种都不支持直接。您必须迭代数据并在迭代时执行reverse delete到位。例如,要仅从上面的data2中提取0th和2nd行,可以使用:

rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
    if i not in rows_to_select:
        del data2[i]

pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

灵丹妙药:嵌套数据的^{}

除了上述方法之外,还有一个强大的替代方法是json_normalize函数,它可以处理字典(记录)列表,此外还可以处理嵌套字典。

pd.io.json.json_normalize(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

pd.io.json.json_normalize(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

同样,请记住,传递给json_normalize的数据必须是字典(记录)格式的列表。

如前所述,json_normalize还可以处理嵌套字典。以下是从文档中获取的示例。

data_nested = [
  {'counties': [{'name': 'Dade', 'population': 12345},
                {'name': 'Broward', 'population': 40000},
                {'name': 'Palm Beach', 'population': 60000}],
   'info': {'governor': 'Rick Scott'},
   'shortname': 'FL',
   'state': 'Florida'},
  {'counties': [{'name': 'Summit', 'population': 1234},
                {'name': 'Cuyahoga', 'population': 1337}],
   'info': {'governor': 'John Kasich'},
   'shortname': 'OH',
   'state': 'Ohio'}
]

pd.io.json.json_normalize(data_nested, 
                          record_path='counties', 
                          meta=['state', 'shortname', ['info', 'governor']])

         name  population    state shortname info.governor
0        Dade       12345  Florida        FL    Rick Scott
1     Broward       40000  Florida        FL    Rick Scott
2  Palm Beach       60000  Florida        FL    Rick Scott
3      Summit        1234     Ohio        OH   John Kasich
4    Cuyahoga        1337     Ohio        OH   John Kasich

有关metarecord_path参数的更多信息,请参阅文档。


总结

下面是上面讨论的所有方法的表,以及支持的特性/功能。

enter image description here

*使用orient='columns',然后转置以获得与orient='index'相同的效果。

在pandas 16.2中,我必须做pd.DataFrame.from_records(d)才能让这个工作。

假设d是你的口述清单,简单地说:

pd.DataFrame(d)

相关问题 更多 >