【问题标题】:Adding a Dictionary as a new row in a data frame将字典添加为数据框中的新行
【发布时间】:2019-01-29 03:38:33
【问题描述】:

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

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

我想让这个函数创建一个数据框,并且在循环中的每次迭代中,索引(或第一列)设置为我的循环的 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...

【问题讨论】:

    标签: python python-3.x pandas dictionary dataframe


    【解决方案1】:

    创建一个值的嵌套字典和函数返回的字典,然后在最后使用 DataFrame 构造函数from_dictorient='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')
    

    输出:

         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
    

    【讨论】:

    • 非常好!像魅力一样工作谢谢。其他答案也很有效!
    【解决方案2】:

    不确定您从值列表中选择对象的确切规则。所以我只是在这里随机选择。但是思路应该差不多:

    value_list = np.random.rand(1000).tolist()
    df = pd.DataFrame()
    for i in range(10, 101, 10):
        a, b, c = random.sample(value_list, 3)
        df.loc[i, 'key1'] = a
        df.loc[i, 'key2'] = b
        df.loc[i, 'key3'] = c
    

    【讨论】:

      猜你喜欢
      • 2020-02-24
      • 2018-05-08
      • 2017-04-22
      • 2021-11-07
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多