【问题标题】:Best way to iterate through dict of pandas dataframes with identical structures, to generate one dataframe with the sum of each (row, col) element?迭代具有相同结构的熊猫数据帧的字典的最佳方法,以生成一个具有每个(行,列)元素总和的数据帧?
【发布时间】:2020-11-04 19:41:07
【问题描述】:

我有一个 pandas dict,d1,其中每个值是一个两列(ID 和权重)、100 行数据框。

我想遍历字典,对于每个数据帧,我想对第 n 行中的所有“权重”值求和,其中 n 是代表该行的 1 到 100 之间的值。然后我想将输出写入另一个字典 d2,其中键为 1-100,值是值的总和。

示例 d1 值数据框:

ID    Weight
1     0.021
2     0.445
3     1.018
..
..
..
99    77.31
100   234.04

基本上,假设我有 10000 个这样的数据帧,我想将 ID 1 的所有权重值加到 10000 中,然后将 ID 2 的所有权重值加到 10000 中,依此类推,直到 ID 100。

我有一个解决方案,基本上是一个嵌套循环。它起作用了,它会起作用的。但是,我真的很想扩展我的基本 pandas / numpy 知识,我想知道是否有更 Python 的方式来做到这一点?

我现有的代码:

for i in range (1,101):
    tot = 0
    for key, value in d1.items():
        tot = tot + value.at[i,'Weight']
    d2[i] = tot

非常感谢任何帮助和建议!

【问题讨论】:

    标签: python pandas numpy dictionary


    【解决方案1】:

    你可以使用pandas添加功能:

    #create a zero filled dataframe
    df = pd.DataFrame(0, index=np.arange(len(df1)), columns=df1.columns)
    #iterate through dict and add values to df
    for value in d1.values():
      df = df.add(value)
    

    您可以通过df_i = df_i.set_index('ID')ID 设置为索引,然后将它们全部相加,这样就只添加权重,最后添加df=df.reset_index()。 示例:

    df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['ID','Weight'])
       ID  Weight
    0   1       2
    1   3       4
    2   5       6
    
    df2 = pd.DataFrame([(10,20),(30,40),(50,60)], columns=['ID','Weight'])
       ID  Weight
    0  10      20
    1  30      40
    2  50      60
    
    df3 = pd.DataFrame([(100,200),(300,400),(500,600)], columns=['ID','Weight'])
        ID  Weight
    0  100     200
    1  300     400
    2  500     600
    
    d1 = {'df1':df1,'df2':df2,'df3':df3}
    df = pd.DataFrame(0, index=np.arange(len(df1)), columns=df1.columns)
    print(df)
    for value in d1.values():
      df = df.add(value)
    

    df:

        ID  Weight
    0  111     222
    1  333     444
    2  555     666
    

    【讨论】:

    • Ehsan,非常感谢您的详细回复——我完全错过了 pandas 的添加功能——这对我以后非常有用。对此,我真的非常感激。一旦我可以投票,我会回复你的回答!编辑:看来我现在可以投票了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多