微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 3 列 Pandas DataFrame 创建矩阵如 2 路表

如何解决从 3 列 Pandas DataFrame 创建矩阵如 2 路表

我有一个这样的数据框,

               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   

解决方法

这就是所谓的枢轴。 Pandas 为此有 pivotpivot_tableset_index/unstack。有关更多详细信息,请参阅 this excellent guide。作为初学者,您可以尝试:

# this extract the time string
df['minute'] = df['datetime'].dt.strftime('%H-%M')

output = df.pivot_table(index='minute',columns='id',values='value')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。