【发布时间】:2019-11-08 01:18:11
【问题描述】:
给一个这样的数据框:
count date location type
0 100 2018-01-01 site1 high
1 10 2018-01-01 site2 low
2 11 2018-01-01 site3 low
3 101 2018-01-03 site2 high
4 103 2018-01-03 site2 high
5 15 2018-01-03 site3 low
我需要找到每天的最高和最低计数(在 mm-dd 格式中,年份无关紧要)。我正在寻找的结果是这样的:
count date location
month-day type
01-01 high 100 2018-01-01 site1
low 10 2018-01-01 site2
01-03 high 103 2018-01-03 site2
low 15 2018-01-03 site3
我有一个可行的方法,但我确信它可以被清理掉。这是我目前所拥有的:
df = pd.DataFrame({'date':['2018-01-01', '2018-01-01', '2018-01-01', '2018-01-03', '2018-01-03', '2018-01-03'],
'location':['site1', 'site2', 'site3', 'site2', 'site2', 'site3'],
'type':['high', 'low', 'low', 'high', 'high', 'low'],
'count':[100, 10, 11, 101, 103, 15]})
df['date'] = pd.to_datetime(df['date'])
df['month-day'] = df['date'].apply(lambda x: x.strftime('%m-%d'))
maxCount = df.loc[df.groupby(['month-day']['type'=='high'])['count'].idxmax()]
minCount = df.loc[df.groupby(['month-day']['type'=='low'])['count'].idxmin()]
df = maxCount.merge(minCount, how='outer')
df.set_index(['month-day', 'type'], inplace=True)
df.sort_index(inplace=True)
这些最终将用作 matplotlib 的输入,以图表计数与月日的低位和高位,因此将它们分开而不是将它们重新组合在一起实际上可能是有意义的,但有没有更好的方法来做这个?特别是 groupby 似乎与][ 有点不确定,但它确实有效。我唯一关心的是月日、类型和计数(并且类型只需要知道它是低还是高,所以如果我使用一个专门的系列来表示低,一个用于高,我就不需要保留输入一次我输入月日并计算在适当的系列中)。
【问题讨论】: