【问题标题】:to group but not using the groupby function of Python/Pandas分组但不使用 Python/Pandas 的 groupby 函数
【发布时间】:2021-07-24 17:47:00
【问题描述】:
INPUT DATA-
array([['00:00:00', 20, 15.27],
       ['00:15:00', 20, 9.07],
       ['00:30:00', 20, 7.33],
       ...,
       ['00:30:00', 407, 34.0],
       ['00:00:00', 407, 172.0],
       ['00:10:00', 407, 187.0]], dtype=object)

第一列 - 时间 第二列 - id 第三列 - 价格

60k+ 行

需要找到每次价格每个 id 的总和。

我正在尝试不使用 GROUPBY 功能

我怎样才能做到这一点?我一直在尝试使用它。

result={}
for t,id,price in trial.inputs():
    result[t]={}
    if id not in result[t]:
        result[t][id]=0
    result[t][id]+=price
print (result)

【问题讨论】:

  • 类似,但我的问题是要我以 10 分钟为间隔进行分组,并进一步根据 ID 对价格总和进行分组。
  • 我们为什么要避免使用pandas 函数?
  • 不使用直接库是一种评估。我正在尝试循环它。我可以使用 for 循环对 id 中的价格进行分组,但无法将时间连接到它。

标签: python pandas dataframe numpy


【解决方案1】:

更新:

from collections import defaultdict
d = defaultdict(list)
for t,id,price in trial:
    d[t,id].append(price)
print (d)

我可以根据 t 和 id 对价格进行分组。如何找到每个 id 的价格总和?

【讨论】:

    【解决方案2】:

    扩展您的答案,您可以再次迭代字典以找到 value 的总和(在本例中为 list

    import numpy as np
    from collections import defaultdict
    
    data_array = np.array([['00:00:00', 20, 15.27],
                           ['00:15:00', 20, 9.07],
                           ['00:30:00', 20, 7.33],
                           ['00:30:00', 407, 34.0],
                           ['00:00:00', 407, 172.0],
                           ['00:10:00', 407, 187.0]], dtype=object)
    
    print(data_array)
    
    # Your solution to store the price values to corresponding [t, id].
    time_id_to_price = defaultdict(list)
    for t, id, price in data_array:
        time_id_to_price[t, id].append(price)
    print(time_id_to_price)
    
    # Make a copy of previous dictionary and assign the sum of values.
    time_id_to_price_sum = time_id_to_price.copy()
    for t, id, price in data_array:
        time_id_to_price_sum[t, id] = sum(time_id_to_price_sum[t, id])
    print(time_id_to_price_sum)
    

    【讨论】:

    • 所以我需要在最终列表中找到价格的总和。我们该怎么做?
    猜你喜欢
    • 2018-01-14
    • 2022-08-02
    • 2021-06-19
    • 1970-01-01
    • 2018-12-20
    • 2015-05-14
    • 2019-08-05
    • 2014-07-16
    • 1970-01-01
    相关资源
    最近更新 更多