如何在Python Pandas中的列中定义的值之间汇总DataFrame中的值?

hsgswve4  于 2022-12-09  发布在  Python
关注(0)|答案(1)|浏览(102)

I have DataFrame in Python Pandas like below:
Data types:

  • MONTH_NR - numeric
  • MONTH_NAME - object
  • VALUE - numeric
MONTH_NRMONTH_NAMEVALUE
1JANUARY10
2FEBRYARY20
3MARCH15
4APRIL10
5MAY11
6JUN100
7JULY200
8AUGUST12
9SEPTEMBER20
10OCTOBER50
11NOVEMBER30
12DECEMBER50

And I need to add 3 new ROWS where will be:

  1. sum of values from column "VALUE" after 6 month (from 1 till 6)
  2. sum of values from column "VALUE" after 12 month (from 7 till 12)
  3. sum of values from column "VALUE" after 12 month (from 1 till 12)
    So as a result I need somethin like below:
MONTH_NR | MONTH_NAME  | VALUE
    ---------|-------------|---------
    1        | JANUARY     |  10
    2        | FEBRYARY    |  20
    3        | MARCH       |  15
    4        | APRIL       |  10
    5        | MAY         |  11
    6        | JUN         |  100
SUM_AFTER_1_6|             |  166
    7        | JULY        |  200
    8        | AUGUST      |  12
    9        | SEPTEMBER   |  20
    10       | OCTOBER     |  50
    11       | NOVEMBER    |  30
    12       | DECEMBER    |  50
SUM_AFTER_7_12|             |  362
SUM_ALL      |             |  528

How can I do that in Python Pandas ?

wpx232ag

wpx232ag1#

建议的方法:

  • 将order_num列添加到df,我的计算月份 * 10
  • 计算汇总行(到另一个df中),order_num = 65(1-6求和)、125(7-12求和)和130(1-12求和)
  • 将计算行添加到原始df
  • 输出按order_num排序的df

相关问题