pie*_*ara 5 python time pandas
我有这样的每小时 csv 数据,每天都这样排序数百天:
2011.05.16,00:00,1.40893
2011.05.16,01:00,1.40760
2011.05.16,02:00,1.40750
2011.05.16,03:00,1.40649
我想计算每天设置的最大值每小时多少次,所以如果在 00:00 我有 2011.05.16 天的最大值,我将 1 添加到 00:00 等等。为此,我使用了一个循环来以这种方式计算像索引一样的小时数:
def graph():
Date, Time, High = np.genfromtxt(myPath, delimiter=",",
unpack = True, converters={0:date_converter})
numList = [""] * 24
index=0
hour=0
count = [0] * 24
for eachHour in Time:
numList[hour] += str(High[index])
index += 1
hour +=1
if hour == 24:
higher = (numList.index(max(numList)))
count[higher] += 1
hour = 0
numList = [""] * 24
Run Code Online (Sandbox Code Playgroud)
问题是,在我的数据中,经常有一些小时缺失的差距,但循环无法识别它并继续将值放入下一小时的索引中。我到处搜索,但我是编程新手,这是我的第一个“复杂”工作,所以我需要更具体的答案来了解它是如何工作的。那么你如何像解释的那样进行每小时频率计数? 最终结果应该是这样的:
00:00 n time max of the day
01:00 n time max of the day
02:00 n time max of the day
etc
Run Code Online (Sandbox Code Playgroud)
首先在csv中读取:
In [11]: df = pd.read_csv('foo.csv', sep=',', header=None, parse_dates=[[0, 1]])
In [12]: df.columns = ['date', 'val']
In [13]: df.set_index('date', inplace=True)
In [14]: df
Out[14]:
val
date
2011-05-16 00:00:00 1.40893
2011-05-16 01:00:00 1.40760
2011-05-16 02:00:00 1.40750
2011-05-16 03:00:00 1.40649
Run Code Online (Sandbox Code Playgroud)
使用 resample 获得每天的最大值:
In [15]: day_max = df.resample('D', how='max')
Run Code Online (Sandbox Code Playgroud)
检查每个值是否为天最大值:
In [16]: df['is_day_max'] = day_max.lookup(df.index.normalize(), len(df) * ['val']) == df.val
In [17]: df
Out[17]:
val is_day_max
date
2011-05-16 00:00:00 1.40893 True
2011-05-16 01:00:00 1.40760 False
2011-05-16 02:00:00 1.40750 False
2011-05-16 03:00:00 1.40649 False
Run Code Online (Sandbox Code Playgroud)
然后每小时总结这些:
In [18]: df.groupby(df.index.time)['is_day_max'].sum()
Out[18]:
00:00:00 1
01:00:00 0
02:00:00 0
03:00:00 0
Name: is_day_max, dtype: float64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5648 次 |
| 最近记录: |