尝试使用python中的熊猫复制sumifs

发布于 2025-02-10 04:06:03 字数 470 浏览 1 评论 0原文

我有一个基本上是这样的数据框:

”位置团队资产P01

我想要这样的输出

它延伸到最后一个时期。

有人确定如何使用python/pandas做到这一点吗?

谢谢!

I have a dataframe that is essentially this:

Location Team  Asset  P01  P02  P03  P04 ... 
England

And I'd like an output that's like this
enter image description here

Where it extends until the last period.

Is anyone sure how to do this using python/pandas?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

锦爱 2025-02-17 04:06:03

您可以将索引设置为“位置”和“资产”,并在所有期间列上使用stack,这将为您提供所需的结构。

然后是groupby.sum()的问题:

df_reshaped = df.set_index(['Asset','Location'])\
    .stack().reset_index()\
        .sort_values(by=['Asset','level_2'])\
            .rename(columns={'level_2':'Period',0:'Cost'})

df_reshaped.groupby(['Asset','Location','Period'],as_index=False).sum()

打印:

   Asset Location Period  Cost
0      A     Scot    P01   163
1      A     Scot    P02   131
2      A     Scot    P03   114
3      A     Scot    P04   176
4      B      Eng    P01   134
5      B      Eng    P02    74
6      B      Eng    P03   112
7      B      Eng    P04    33
8      C      Eng    P01    85
9      C      Eng    P02    90
10     C      Eng    P03    19
11     C      Eng    P04    68
12     C     Scot    P01    51
13     C     Scot    P02    95
14     C     Scot    P03    79
15     C     Scot    P04    62

You could set your index to be "Location" and "Asset" and use stack on all the Period columns which would get you the structure you are looking for.

Then it's a matter of groupby.sum():

df_reshaped = df.set_index(['Asset','Location'])\
    .stack().reset_index()\
        .sort_values(by=['Asset','level_2'])\
            .rename(columns={'level_2':'Period',0:'Cost'})

df_reshaped.groupby(['Asset','Location','Period'],as_index=False).sum()

prints:

   Asset Location Period  Cost
0      A     Scot    P01   163
1      A     Scot    P02   131
2      A     Scot    P03   114
3      A     Scot    P04   176
4      B      Eng    P01   134
5      B      Eng    P02    74
6      B      Eng    P03   112
7      B      Eng    P04    33
8      C      Eng    P01    85
9      C      Eng    P02    90
10     C      Eng    P03    19
11     C      Eng    P04    68
12     C     Scot    P01    51
13     C     Scot    P02    95
14     C     Scot    P03    79
15     C     Scot    P04    62
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文