![](/img/trans.png)
[英]Pandas Dataframe - record number of rows based on cumulative sum on a column with a condition
[英]Pandas cumulative sum on column with condition
我沒有在其他地方找到答案,所以我需要問一下。 可能是因為我不知道如何正確命名它。 (英語不是我的原始語言)
我有大的日期時間數據框。 時間在這里很重要。 df中的一列具有值[Nan,1,-1]。 我需要執行快速計算,以便在值發生變化時進行累積和重置。
例。
Time sign desire_value
2014-01-24 05:00:00 Nan Nan
2014-01-24 06:00:00 Nan Nan
2014-01-24 07:00:00 Nan Nan
2014-01-24 08:00:00 1 1
2014-01-24 09:00:00 1 2
2014-01-24 10:00:00 1 3
2014-01-24 11:00:00 -1 1
2014-01-24 12:00:00 -1 2
2014-01-24 13:00:00 -1 3
2014-01-24 14:00:00 -1 4
2014-01-24 15:00:00 -1 5
2014-01-24 16:00:00 1 1
2014-01-24 17:00:00 1 2
2014-01-24 18:00:00 1 3
2014-01-24 19:00:00 -1 1
2014-01-24 20:00:00 -1 2
2014-01-24 21:00:00 1 1
2014-01-24 22:00:00 1 2
我有使用函數的工作解決方案,但效率不高。
df['sign_1'] = df['sign'].shift(1)
for index, row in df.iterrows():
if row.sign is None:
df.loc[line, 'desire_value'] = None
elif row.sign == row.sign_1:
acc += 1
df.loc[index, 'desire_value'] = acc
else:
acc = 1
df.loc[index, 'desire_value'] = acc
我找不到任何基於陣列的方法。 我發現在Python中有效迭代的最好方法是使用Cython,但是有更多“Python”方法來解決這個問題嗎?
請看這里的最后一節
這是像groupby這樣的itertools
In [86]: v = df['value'].dropna()
石斑魚在群斷點處分開; cumsum使它有單獨的組
In [87]: grouper = (v!=v.shift()).cumsum()
In [88]: grouper
Out[88]:
3 1
4 1
5 1
6 2
7 2
8 2
9 2
10 2
11 3
12 3
13 3
14 4
15 4
16 5
17 5
Name: value, dtype: int64
然后只是一個簡單的cumsum
In [89]: df.groupby(grouper)['value'].cumsum()
Out[89]:
0 NaN
1 NaN
2 NaN
3 1
4 2
5 3
6 -1
7 -2
8 -3
9 -4
10 -5
11 1
12 2
13 3
14 -1
15 -2
16 1
17 2
dtype: float64
如果你確實想要絕對值,你當然可以.abs()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.