Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字典列表转换为数据帧_Python_Dictionary_Pandas_Dataframe - Fatal编程技术网

Python 将字典列表转换为数据帧

Python 将字典列表转换为数据帧,python,dictionary,pandas,dataframe,Python,Dictionary,Pandas,Dataframe,我有一个这样的字典列表: [{'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

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

[{'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
dict_count = len(dict_list)
df = pd.DataFrame(dict_list[0], index=[0])
for i in range(1,dict_count-1):
    df = df.append(dict_list[i], ignore_index=True)
我想把它变成一个熊猫
数据帧
,如下所示:

[{'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
dict_count = len(dict_list)
df = pd.DataFrame(dict_list[0], index=[0])
for i in range(1,dict_count-1):
    df = df.append(dict_list[i], ignore_index=True)
注意:列的顺序并不重要


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

假设
d
是您的dict列表,简单地说:

df = pd.DataFrame(d)

注意:这不适用于嵌套数据。

在pandas 16.2中,我必须执行
pd.DataFrame.from_records(d)
才能使其工作。

您也可以使用
pd.DataFrame.from_dict(d)
如下:

In [8]: d = [{'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'}]

In [12]: pd.DataFrame.from_dict(d)
Out[12]: 
      month  points  points_h1  time    year
0       NaN    50.0        NaN  5:00  2010.0
1  february    25.0        NaN  6:00     NaN
2   january    90.0        NaN  9:00     NaN
3      june     NaN       20.0   NaN     NaN
如何将字典列表转换为数据帧? 其他答案都是正确的,但就这些方法的优点和局限性而言,解释得并不多。这篇文章的目的是展示这些方法在不同情况下的示例,讨论何时使用(何时不使用),并提出替代方案


,及 根据数据的结构和格式,在某些情况下,这三种方法要么都有效,要么有些比其他方法更好,要么根本不起作用

考虑一个非常做作的例子

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'
在继续之前,重要的是区分不同类型的词典定位,并使用pandas进行支持。有两种主要类型:“列”和“索引”

orient='columns'

具有“columns”方向的字典将使其键对应于等效数据框中的列

例如,上面的
数据
处于“列”方向

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

orient='index'

根据此方向,假定键对应于索引值。这类数据最适合于来自_dict的pd.DataFrame

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}}
OP中未考虑此情况,但了解此情况仍然很有用

设置自定义索引 如果需要在结果数据帧上设置自定义索引,可以使用
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.的
支持

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}}
处理缺少的键/列 当处理缺少键/列值的字典时,所有方法都是现成的。比如说,

data2 = [
     {'A': 5, 'C': 3, 'D': 3},
     {'A': 7, 'B': 9, 'F': 5},
     {'B': 4, 'C': 7, 'E': 6}]
读取列的子集 “如果我不想读每一列怎么办?”?您可以使用
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
默认方向为“列”的dict的pd.DataFrame.from不支持这一点

读取行的子集 这些方法中的任何一种都不直接支持。您必须在数据上进行迭代,并在迭代过程中执行就地测试。例如,要从上面的
data2
中仅提取第0行和第2行,您可以使用:

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\u normalize
函数,它可以处理字典(记录)列表,此外还可以处理嵌套字典

pd.json_normalize(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6
同样,请记住,传递给
json\u normalize
的数据需要采用字典列表(记录)格式

如前所述,
json\u 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'}
]
有关
记录路径
参数的更多信息,请查看文档

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'}
]

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


*使用
orient='columns'
然后转置以获得与
orient='index'
相同的效果。我发现最简单的方法如下:

[{'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
dict_count = len(dict_list)
df = pd.DataFrame(dict_list[0], index=[0])
for i in range(1,dict_count-1):
    df = df.append(dict_list[i], ignore_index=True)
Pyhton3: 前面列出的大多数解决方案都是有效的。但是,在某些情况下,不需要数据帧的行号,并且必须单独写入每一行(记录)

在这种情况下,以下方法很有用


要将字典列表转换为数据帧,可以使用“追加”:

我们有一个名为dic的字典,dic有30个列表项(
list1
list2
,…,
list30

  • 步骤1:定义用于保存结果的变量(例如:
    total\u df
  • 步骤2:使用
    list1
  • 步骤3:使用“for loop”将所有列表附加到
    total\u df

  • 这种方法的好处是,它也适用于
    deque
    如果字典没有相同的键,那么必须使用
    from_records
    ,如果字典没有相同的键,那么使用@joris solutionUsinig 0.14.1和@joris'解决方案也可以值对作为索引(例如时间)?@CatsLoveJazz您只需执行
    df=df.set_索引('time'))
    afterwards@CatsLoveJazz不,当从dict转换时,这是不可能的。从Pandas 0.19.2开始,文档中没有提到这一点,至少在
    Pandas.DataFrame的文档中没有提到。请注意,对于嵌套字典
    “{”“:{”…
    如果使用json_normalize方法,请参见@cs95的详细答案。问题是如何从
    dict
    s列表中构造数据帧,而不是像您假设的那样从单个
    dict
    中构造数据帧
    import csv
    
    my file= 'C:\Users\John\Desktop\export_dataframe.csv'
    
    records_to_save = data2 #used as in the thread. 
    
    
    colnames = list[records_to_save[0].keys()] 
    # remember colnames is a list of all keys. All values are written corresponding
    # to the keys and "None" is specified in case of missing value 
    
    with open(myfile, 'w', newline="",encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(colnames)
        for d in records_to_save:
            writer.writerow([d.get(r, "None") for r in colnames])
    
    total_df=list1
    nums=Series(np.arange(start=2, stop=31))
    for num in nums:
        total_df=total_df.append(dic['list'+str(num)])