gpt4 book ai didi

python - 在 Pandas Python 中加入/搜索/求和

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:25 24 4
gpt4 key购买 nike

我是 Panda 的新手,正在尝试学习它,我在 Panda 中有一个包含 3 个不同列的 DataFrame:

   a             b         c
-----------------------------
' Alice 5/5/2014 2 '
' Bob 7/18/2014 1 '
' Alice 5/5/2014 3 '
' Bob 8/10/2014 5 '
------------------------------

我想总结每个人每月的“C”列,因此期望的结果如下:

   a             b         c
-----------------------------
' Alice 5/5/2014 5 '
' Bob 7/18/2014 1 '
' Bob 8/10/2014 5 '
------------------------------

在 Panda 中执行此操作的最佳方法是什么。

如果我的问题重复出现,请将我重定向到我找不到的其他问题,这可能是因为我不确定要查找什么。谢谢

最佳答案

最有效的方法是首先确保您的日期列是 datetime 类型:

>>> df2
a b c
0 Alice 5/5/2014 2
1 Bob 7/18/2014 1
2 Alice 5/9/2014 3
3 Bob 8/10/2014 5
>>> df2['b'] = pd.to_datetime(df2.b)

然后,按日期列索引 DataFrame:

>>> df2.set_index('b',inplace=True)
>>> df2
a c
b
2014-05-05 Alice 2
2014-07-18 Bob 1
2014-05-09 Alice 3
2014-08-10 Bob 5

然后使用groupby:

>>> df2.groupby(['a',df2.index.month]).sum()
c
a
Alice 5 5
Bob 7 1
8 5
>>>

而且您始终可以返回到原始索引:

>>> df2.reset_index(inplace=True)
>>> df2
b a c
0 2014-05-05 Alice 2
1 2014-07-18 Bob 1
2 2014-05-09 Alice 3
3 2014-08-10 Bob 5

关于python - 在 Pandas Python 中加入/搜索/求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39925423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com