我一直在研究 Pandas 中一个公开可用的数据集,其中包含美国每个州的一些空气质量统计数据。
我正在做的是汇总每个州的测量值,我遇到的问题是不同的州在不同的时间段有可用的测量值。所以,我正在收集所有数据如下:
import pandas as pd
poll = pd.read_csv('dataset.csv')
poll = poll.groupby(['State', 'Date Local']).mean()
states = pds.index.levels[0] # All the states
pds_grouped = pds.groupby(level='State')
# Iterate throuugh each of the state and aggregae monthly
for s in states:
flt = pds_grouped.get_group(s).groupby(pd.Grouper(level='Date Local', freq='M')).agg({'V1': 'mean',
'V2': 'mean',
'V3': 'mean',
'V4': 'mean'})
print(s, flt.shape, flt.index.min(), flt.index.max(), type(flt))
这会打印如下内容:
Alabama (30, 4) 2013-12-31 00:00:00 2016-05-31 00:00:00 <class 'pandas.core.frame.DataFrame'>
Alaska (18, 4) 2014-07-31 00:00:00 2015-12-31 00:00:00 <class 'pandas.core.frame.DataFrame'>
Arizona (195, 4) 2000-01-31 00:00:00 2016-03-31 00:00:00 <class 'pandas.core.frame.DataFrame'>
Arkansas (111, 4) 2007-01-31 00:00:00 2016-03-31 00:00:00 <class 'pandas.core.frame.DataFrame'>
California (196, 4) 2000-01-31 00:00:00 2016-04-30 00:00:00 <class 'pandas.core.frame.DataFrame'>
Colorado (195, 4) 2000-01-31 00:00:00 2016-03-31 00:00:00 <class 'pandas.core.frame.DataFrame'>
Connecticut (117, 4) 2006-04-30 00:00:00 2015-12-31 00:00:00 <class 'pandas.core.frame.DataFrame'>
正如您所看到的,它们都有不同数量的测量,并且它们也跨越不同的时间段。我正在尝试创建一个动画,显示这些污染物在整个时间内的变化,如果我可以在同一时间段内获取这些数据帧并基本上用NaNs
与测量所在的时间段相对应的时间段填充它会容易得多不适用于给定状态。我一直在看resample
熊猫中的方法,但无法弄清楚如何指定日期范围。
尝试:
all_dates = poll.index.levels[1]
date_range = pd.date_range(all_dates.min(), all_dates.max(), freq='MS')
flt = (poll.groupby('State')
.apply(lambda x: x.reset_index(level=1)
.resample('MS', on='Date Local')
.mean()
.reindex(date_range))
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句