我用时间戳标记了每个常规时间段的非常规条目数的数据。也就是说,有时我可以在一秒钟内拥有25个条目,而另一些时候我可以在一秒钟内拥有100个条目(这是财务数据)。
为了创建一个新的数据库,我想在定义的时间段内随机选择一个条目,比如前半秒和后半秒,以减少数据集的大小,并在条目中创建一致性。我如何在熊猫中做到这一点?
非常感谢。
发布于 2020-06-06 07:21:37
可能不是最好的,但我认为它是有效的:resample您的DataFrame/系列除以您想要的秒,然后从每个bin中随机选择一行(如果没有数据,则放入NaN ):
import pandas as pd
import numpy as np
#making fake date, randomly picked times in a minute at 100ms frequency
dr = pd.date_range('01-01-2020 9:00:00', '01-01-2020 9:01:00', freq='100ms')
dates = sorted(np.random.choice(dr, size=100))
df = pd.DataFrame(index=dates,data=np.random.random(size=(100,2)),columns=['Values','Values2'])
#resample
resampled = df.resample('500ms')
#iterate over resampled, and pick a random row (if there, else np.nan)
output = pd.DataFrame(columns=df.columns)
for time,frame in resampled:
if not frame.empty:
random_index = np.random.choice(range(len(frame.index)))
output.loc[time] = list(frame.iloc[random_index])
else:
output.loc[time] = np.nan输入:
#df.head(10)
Values Values2
2020-01-01 09:00:00.100 0.190373 0.831841
2020-01-01 09:00:00.200 0.218069 0.586812
2020-01-01 09:00:00.500 0.611154 0.603198
2020-01-01 09:00:00.900 0.076038 0.061462
2020-01-01 09:00:00.900 0.519908 0.259880
2020-01-01 09:00:00.900 0.652016 0.925601
2020-01-01 09:00:01.000 0.256711 0.586374
2020-01-01 09:00:01.300 0.939387 0.409488
2020-01-01 09:00:01.400 0.075527 0.691568
2020-01-01 09:00:01.400 0.283443 0.490719输出:
#output.head(3)
Values Values2
2020-01-01 09:00:00.000 0.190373 0.831841
2020-01-01 09:00:00.500 0.652016 0.925601
2020-01-01 09:00:01.000 0.256711 0.586374https://stackoverflow.com/questions/62224910
复制相似问题