如何对这些数据进行分组、进行计算和筛选?

huangapple go评论91阅读模式
英文:

How can I group this data and make this calculations and drops?

问题

我有这些数据:

  1. 0 1.514333e+12
  2. 1 1.514419e+12
  3. 2 1.514506e+12
  4. 3 1.514592e+12
  5. 4 1.514678e+12
  6. ...
  7. 1881 1.676851e+12
  8. 1882 1.676938e+12
  9. 1883 1.677024e+12
  10. 1884 1.677110e+12
  11. 1885 1.677146e+12
  12. Name: volume1d, Length: 1886, dtype: float64

这些数据按时间段排列,因此我需要将这些数据每4行分组(每4个小时,每行代表一个小时)。例如:

  1. a b
  2. 1 2
  3. 1 3
  4. 1 4
  5. 1 4
  6. 2 3
  7. 2 4
  8. 2 5
  9. 2 4
  10. 3 4

之后,我需要将这些分组相加,得到:

  1. a b c
  2. 1 2 2
  3. 1 3 5
  4. 1 4 9
  5. 1 4 13
  6. 2 3 3
  7. 2 4 7
  8. 2 5 12
  9. 2 4 16
  10. 3 4 4

最后,只保留每个分组的最后一行:

  1. a b c
  2. 1 4 13
  3. 2 4 16
  4. 3 4 4

如何能完成这个任务?(我只需要最后一张表格,如果您找到其他方法来完成这个任务,那就更好了)

编辑:如果最后一组只包含1、2或3行,我希望将这些行相加。

英文:

I have this data:

  1. 0 1.514333e+12
  2. 1 1.514419e+12
  3. 2 1.514506e+12
  4. 3 1.514592e+12
  5. 4 1.514678e+12
  6. ...
  7. 1881 1.676851e+12
  8. 1882 1.676938e+12
  9. 1883 1.677024e+12
  10. 1884 1.677110e+12
  11. 1885 1.677146e+12
  12. Name: volume1d, Length: 1886, dtype: float64

The data is in timeperiods, so, I need to group this data every 4 rows (every 4 hours (each row is an hour)).
for example:

  1. a b
  2. 1 2
  3. 1 3
  4. 1 4
  5. 1 4
  6. 2 3
  7. 2 4
  8. 2 5
  9. 2 4
  10. 3 4

after this, I would have to add the groups.

  1. a b c
  2. 1 2 2
  3. 1 3 5
  4. 1 4 9
  5. 1 4 13
  6. 2 3 3
  7. 2 4 7
  8. 2 5 12
  9. 2 4 16
  10. 3 4 4

to finish leaving just the las row of the groups:

  1. a b c
  2. 1 4 13
  3. 2 4 16
  4. 3 4 4

How can I all do this?
(what I need is the last table, so if you find another way to do this, perfect)

Edited: if the last group is only contains 1,2 or 3 rows, I would like it to have those rows added.

答案1

得分: 0

您可以使用累积求和(cumsum函数)来转换记录,并最终提取每个组的最后一条记录:

  1. df.assign(c=df.groupby('a').transform('cumsum')).groupby('a').last().reset_index()

这段代码将会对数据进行相应的操作。如果您需要进一步了解代码中的函数和方法,请查看这里

英文:

You can transform records using cumulative sum (cumsum function) and eventually extract the last record from each group:

  1. df.assign(c=df.groupby('a').transform('cumsum')).groupby('a').last().reset_index()

  1. a b c
  2. 0 1 4 13
  3. 1 2 4 16
  4. 2 3 4 4

huangapple
  • 本文由 发表于 2023年2月23日 19:30:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定