gpt4 book ai didi

python - 遍历 pandas 中的 groupby 字段

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:33 25 4
gpt4 key购买 nike

我一直致力于 pandas 中的公开可用数据集,其中包含美国各州的一些空气质量统计数据。

我将他的数据集加载到 pandas 数据框中,并使用 groupbystate 对事物进行分组。所以像这样:

import pandas as pd
poll = pd.read_csv(`dataset.csv')
poll = poll.groupby(['State', 'Date Local']).mean()
ds_gb_state = poll.groupby(level='State')

打印这个会得到类似的东西:

                        V1         V2          V3        V4
State Date Local
Alabama 2013-12-01 37.000000 24.000000 1.000000 6.000000
2013-12-02 30.000000 12.000000 3.000000 6.000000
2013-12-03 21.000000 11.000000 3.000000 3.000000
2013-12-04 18.000000 13.000000 1.000000 2.000000
2013-12-05 15.000000 13.000000 1.000000 2.000000
Alaska 2014-07-01 4.000000 16.000000 6.000000 3.000000
2014-07-02 4.000000 15.000000 6.000000 3.000000
2014-07-03 6.000000 19.000000 13.000000 3.000000

我的问题很简单。使用此 ds_gb_state 对象,我如何找到所有州的名称?在此对象中,列是 V1、V2、V3 和 V4,我可以很好地访问它们,但是是否可以枚举所有状态或从该对象中找到最小和最大日期?

最佳答案

How can I find the names of all the states?

您可以使用 MultiIndex.get_level_values :

df.index.get_level_values(0).unique()
# Index(['Alabama', 'Alaska'], dtype='object')

is it possible to find the minimum and maximum dates from this object?

与日期类似:

df.index.get_level_values(1).map(pd.to_datetime).min()
# Timestamp('2013-12-01 00:00:00')

关于python - 遍历 pandas 中的 groupby 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56047663/

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