gpt4 book ai didi

python - 在数据框中添加字典作为新行

转载 作者:太空狗 更新时间:2023-10-30 01:11:17 26 4
gpt4 key购买 nike

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

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

我想让这个函数创建一个数据框,并且在循环的每次迭代中,索引(或第一列)设置为循环的第 i 个值,行将是生成的字典。 .

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

start = 10
stop = 100
step = 10

最终结果应该是这样的:

    key1  key2  key3
10 46 100 200
20 50 75 60
30 80 2 10
40 100 50 6
50 10 8 33
etc...

最佳答案

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

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')

输出:

     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

关于python - 在数据框中添加字典作为新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51974256/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com