【问题标题】:Sum DF columns stored in dictionary [closed]Sum DF 列存储在字典中[关闭]
【发布时间】:2020-04-21 09:39:42
【问题描述】:

我有一个包含 3 个数据帧的字典 {0: DataFrame, 1: DataFrame, 2: DataFrame}。
每个 DataFrame 具有相同的大小。 6 个变量,25 行。 我想对每个 DataFrame 列“收入”中的所有值/行求和,并将总和传递给一个列表。
看起来像这样

list_of_sums = [Sum of income DF0, Sum of income DF1, Sum of income DF2]

【问题讨论】:

标签: python list loops dataframe dictionary


【解决方案1】:

在下面试试这个:

list_of_sums = []
input_dict = {0: DataFrame, 1: DataFrame, 2: DataFrame}
for obj in input_dict:
    list_of_sums.append(input_dict[obj]['Income'].sum())   # use sum function and append the result to the output list.
print(list_of_sums)

【讨论】:

    【解决方案2】:

    不是最优化的,但这是可行的。

    import pandas as pd
    d, dd, ddd = pd.DataFrame(),pd.DataFrame(),pd.DataFrame()
    d['Income'] = [3,4,5,6] 
    dd['Income'] = [30,40,50,60]
    ddd['Income'] = [300,400,500,600]
    
    dicts = [d,dd,ddd]
    for dc in dicts:
        print(sum([s for s in dc['Income']]))
    

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2018-10-11
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      相关资源
      最近更新 更多