【发布时间】:2017-05-23 14:11:21
【问题描述】:
在论坛获得一些帮助后,我设法完成了我正在寻找的事情,现在我需要更上一层楼。 (长解释在这里: Python Data Frame: cumulative sum of column until condition is reached and return the index):
我有一个数据框:
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
然后我将条件应用于cumsumcolumn 并提取满足条件且具有给定容差的行的相应值:
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 功能的解决方案..
【问题讨论】:
标签: python arrays pandas dataframe