การลดอาร์เรย์จำนวนมากสำหรับการวาดแผนภูมิ

ฉันต้องการวาดแผนภูมิในแอปพลิเคชันหลามของฉัน แต่อาร์เรย์ numpy ของแหล่งที่มามีขนาดใหญ่เกินไปสำหรับการทำเช่นนี้ (ประมาณ 1'000'000+) ฉันต้องการหาค่าเฉลี่ยขององค์ประกอบข้างเคียง แนวคิดแรกคือการทำในรูปแบบ C++:

step = 19000 # every 19 seconds (for example) make new point with neam value
dt = <ordered array with time stamps>
value = <some random data that we want to draw>

index = dt - dt % step
cur = 0
res = []

while cur < len(index):
    next = cur
    while next < len(index) and index[next] == index[cur]:
        next += 1
    res.append(np.mean(value[cur:next]))
    cur = next

แต่วิธีนี้ทำงานช้ามาก ฉันพยายามทำ สิ่งนี้:

step = 19000 # every 19 seconds (for example) make new point with neam value
dt = <ordered array with time stamps>
value = <some random data that we want to draw>

index = dt - dt % step
data = np.arange(index[0], index[-1] + 1, step)
res = [value[index == i].mean() for i in data]
pass

วิธีแก้ปัญหานี้ช้ากว่าวิธีแรก ทางออกที่ดีที่สุดสำหรับปัญหานี้คืออะไร?


person Artem Mezhenin    schedule 20.06.2012    source แหล่งที่มา


คำตอบ (1)


np.histogram สามารถให้ผลรวมเหนือถังขยะตามอำเภอใจ หากคุณมีอนุกรมเวลา เช่น:

import numpy as np

data = np.random.rand(1000)          # Random numbers between 0 and 1
t = np.cumsum(np.random.rand(1000))  # Random time series, from about 1 to 500

จากนั้นคุณสามารถคำนวณผลรวมที่รวมไว้ในช่วงเวลา 5 วินาทีโดยใช้ np.histogram:

t_bins = np.arange(0., 500., 5.)       # Or whatever range you want
sums = np.histogram(t, t_bins, weights=data)[0]

หากคุณต้องการค่าเฉลี่ยมากกว่าผลรวม ให้ลบตุ้มน้ำหนักออกแล้วใช้การนับแบบถังขยะ:

means = sums / np.histogram(t, t_bins)][0]

วิธีนี้คล้ายกับวิธีในคำตอบนี้

person marshall.ward    schedule 20.06.2012