在論壇中的一些幫助後,我設法做我正在尋找的東西,現在我需要得到到下一個級別。 (長解釋是在這裏: Python Data Frame: cumulative sum of column until condition is reached and return the index):Python:遍歷數據框列,檢查存儲在數組中的條件值,並獲取值列表
我有一個數據幀:
In [3]: df
Out[3]:
index Num_Albums Num_authors
0 0 10 4
1 1 1 5
2 2 4 4
3 3 7 1000
4 4 1 44
5 5 3 8
我添加一列與另一列的累積總和。
In [4]: df['cumsum'] = df['Num_Albums'].cumsum()
In [5]: df
Out[5]:
index Num_Albums Num_authors cumsum
0 0 10 4 10
1 1 1 5 11
2 2 4 4 15
3 3 7 1000 22
4 4 1 44 23
5 5 3 8 26
然後,我申請到cumsum
列的條件,我提取其中滿足條件與給定公差行的相應值:
In [18]: tol = 2
In [19]: cond = df.where((df['cumsum']>=15-tol)&(df['cumsum']<=15+tol)).dropna()
In [20]: cond
Out[20]:
index Num_Albums Num_authors cumsum
2 2.0 4.0 4.0 15.0
現在,我要做的是在示例中替代條件15
,條件存儲在一個數組中。檢查條件是否滿足,並檢索不是整行,而只檢索列的值Num_Albums
。最後,所有這些檢索值(每個條件一個)存儲在數組或列表中。 從MATLAB來,我會做這樣的事情(我這個混合MATLAB/Python語法道歉):
conditions = np.array([10, 15, 23])
for i=0:len(conditions)
retrieved_values(i) = df.where((df['cumsum']>=conditions(i)-tol)&(df['cumsum']<=conditions(i)+tol)).dropna()
因此對於數據幀以上我會得到(爲tol=0
):
retrieved_values = [10, 4, 1]
我想要一個解決方案,可以讓我保留.where
函數,如果可能的話。
我不斷收到:IndexError:索引0超出0軸的大小0 – AMaz
@Amaz是第一個選項還是第二個選項?第一將是indexError,因爲它需要.values [0],需要事先驗證,讓我爲你編輯 –