我有一个这样的数据框架,
datetime id value
0 2021-02-21 15:43:00 154 0.102677
1 2021-02-21 15:57:00 215 0.843945
2 2021-02-21 00:31:00 126 0.402851
3 2021-02-21 16:38:00 61 0.138945
4 2021-02-21 05:11:00 124 0.865435
.. ... ... ...
115 2021-02-21 21:54:00 166 0.108299
116 2021-02-21 17:39:00 192 0.129267
117 2021-02-21 01:56:00 258 0.300448
118 2021-02-21 20:35:00 401 0.119043
119 2021-02-21 09:16:00 192 0.587173
我可以通过发出
import datetime
from numpy import random
#all minutes of the day, ordered, unique
d = pd.date_range("2021-02-21 00:00:00","2021-02-21 23:59:59", freq="1min")
d2 = pd.Series(d).sample(120,replace=True)
ids = random.randint(1,500,size=d2.shape[0])
df = pd.DataFrame({'datetime':d2,'id':ids,'value':random.random(size=d2.shape[0])})
df.reset_index(inplace=True,drop=True)
,我想把它放在一个矩阵中,一个索引是一天中的分钟,另一个索引是id,也就是1440*unique(ids).shape[0]
请注意,即使一些分钟没有出现在数据框中,输出矩阵无论如何都是1440。
我可以这样做,
但是这需要很长时间。我怎样才能做得更好?
#all ids, unique
uniqueIds = df.id.unique()
idsN = ids.shape[0]
objectiveMatrix = np.zeros([1440,idsN])
mins = pd.date_range(start='2020-09-22 00:00', end='2020-09-23 00:00', closed=None, freq='1min')
for index, row in df.iterrows():
a = np.where(row.id==uniqueIds)[0]
b = np.where(row.datetime==d)[0]
objectiveMatrix[b,a] = row.value
这就是所谓的枢轴。熊猫有pivot
,pivot_table
,set_index/unstack
。要了解更多细节,请参阅这个优秀的指南。作为初学者,您可以尝试:
# this extract the time string
df['minute'] = df['datetime'].dt.strftime('%H-%M')
output = df.pivot_table(index='minute', columns='id', values='value')