[英]Pandas: How to efficiently diff() after a groupby() operation?
我在 Pandas 中確實有一個大型數據集(大約 800 萬行 x 25 列),我正在努力在數據子集上以高性能方式使用 diff() function。
這是我的數據集的樣子:
prec type
location_id hours
135 78 12.0 A
79 14.0 A
80 14.3 A
81 15.0 A
82 15.0 A
83 15.0 A
84 15.5 A
prec
列上的每個位置應用 diff() function。 原始數據集堆積了prec
數字; 通過應用 diff() 我將獲得每小時適當的prec
值。# Filter the data first
df_filtered = df_data[df_data.type == "A"] # only work on locations with 'A' type
df_filtered = df_filtered.query('hours > 0 & hours <= 120') # only work on certain hours
# Apply the diff()
for location_id, data_of_location in df_filtered.groupby(level="location_id"):
df_data.loc[data_of_location.index, "prec"] = data_of_location.prec.diff().replace(np.nan, 0.0)
del df_filtered
df_data
數據幀消耗的memory沒有變化,但整個過程memory消耗上升。來自@Quang Hoang 和@Ben 的輸入。 T,我想出了一個非常快但仍然消耗大量 memory 的解決方案。
# Filter the data first
df_filtered = df_data[df_data.type == "A"] # only work on locations with 'A' type
df_filtered = df_filtered.query('hours > 0 & hours <= 120') # only work on certain hours
# Apply the diff()
df_diffed = df_data.groupby(level="location_id").prec.diff().replace(np.nan, 0.0)
df_data[df_diffed.index, "prec"] = df_diffed
del df_diffed
del df_filtered
我猜可以做兩件事來改善 memory 的使用:
df_filtered
似乎是數據的副本; 那應該會增加很多 memory。df_diffed
也是一個副本。 在計算這兩個變量時,memory 的使用非常密集。 我不確定是否有任何in-place
方式來執行此類操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.