将(部分)numpy 重新数组转换为二维数组?
我们有一组单独日期的数据重新排列 - 第一个属性是时间戳,其余的是值。
其中几个:
ts a b c
2010-08-06 08:00, 1.2, 3.4, 5.6
2010-08-06 08:05, 1.2, 3.4, 5.6
2010-08-06 08:10, 1.2, 3.4, 5.6
2010-08-06 08:15, 2.2, 3.3, 5.6
2010-08-06 08:20, 1.2, 3.4, 5.6
我们希望生成每个值的平均值的数组(就好像您将所有一天的数据放在一起,并对所有排列的值进行平均)。时间戳时间全部匹配,因此我们可以通过创建一个带有时间戳的结果记录来实现,其他列全为 0,然后执行以下操作:
for day in day_data:
result.a += day.a
result.b += day.b
result.c += day.c
result.a /= len(day_data)
result.b /= len(day_data)
result.c /= len(day_data)
似乎更好的方法是将每一天转换为二维数组只是数字(去掉时间戳),然后在一次操作中对所有元素进行平均,但我们找不到一种方法来做到这一点 - 它始终是一个一维对象数组。
有谁知道该怎么做?
We've got a set of recarrays of data for individual days - the first attribute is a timestamp and the rest are values.
Several of these:
ts a b c
2010-08-06 08:00, 1.2, 3.4, 5.6
2010-08-06 08:05, 1.2, 3.4, 5.6
2010-08-06 08:10, 1.2, 3.4, 5.6
2010-08-06 08:15, 2.2, 3.3, 5.6
2010-08-06 08:20, 1.2, 3.4, 5.6
We'd like to produce an array of the averages of each of the values (as if you laid all of the day data on top of each other, and averaged all of the values that line up). The timestamp times all match up, so we can do it by creating a result recarray with the timestamps, and the other columns all 0s, then doing something like:
for day in day_data:
result.a += day.a
result.b += day.b
result.c += day.c
result.a /= len(day_data)
result.b /= len(day_data)
result.c /= len(day_data)
It seems like a better way would be to convert each day to a 2d array with just the numbers (lopping off the timestamps), then average them all element-wise in one operation, but we can't find a way to do this - it's always a 1d array of objects.
Does anyone know how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几种方法可以做到这一点。一种方法是选择重新数组的多个列并将它们转换为浮点数,然后重新整形回二维数组:
或者,您可以考虑这样的方法(速度慢一点,但更具可读性):
另请注意,这可能是一个好主意查看 pandas 等操作,以便您可以轻松地处理异构数据。
There are several ways to do this. One way is to select multiple columns of the recarray and cast them as floats, then reshape back into a 2D array:
Alternatively, you might consider something like this (negligibly slower, but more readable):
Also note that it might be a good idea to look into pandas for operations such as these so that you can easily work with heterogeneous data.