将词典添加为数据框中的新行

nov*_*aly 5 python dictionary dataframe python-3.x pandas

我有一个函数返回键和结果的字典.

我想创建一个循环不同值的新函数.每个值都会产生一个不同结果但具有相同键的新字典.

我想让这个函数创建一个数据帧,并且每次迭代通过循环,索引(或第一列)被设置为我的循环的i值,行将是结果字典..

字典看起来像 {key1: 46, key2:100,key3:200}

start = 10
stop = 100
step = 10
Run Code Online (Sandbox Code Playgroud)

最终结果如下:

    key1  key2  key3
10   46   100    200
20   50    75     60
30   80     2     10
40   100    50     6
50   10     8      33
etc...
Run Code Online (Sandbox Code Playgroud)

ALo*_*llz 4

创建值的嵌套字典和函数返回的字典,然后在最后from_dict使用DataFrame 构造函数。orient='index'

import pandas as pd
import numpy as np
np.random.seed(123)

start = 10
stop = 100
step = 10

d2 = {}
while start <= stop:
    # Simulating your function that returns a dictionary:
    d = {'key1': np.random.randint(1,100), 
         'key2': np.random.randint(1,10), 
         'key3': np.random.randint(20,70)}
    # Add that dictionary to a dictionary
    d2[start] = d
    start+=step

pd.DataFrame.from_dict(d2, orient='index')
Run Code Online (Sandbox Code Playgroud)

输出:

     key1  key2  key3
10     67     3    58
20     18     4    62
30     58     7    53
40     97     2    67
50     74     1    66
60     97     4    34
70     37     1    36
80     69     2    23
90      3     5    59
100    67     5    67
Run Code Online (Sandbox Code Playgroud)