我使用的是pandas数据帧,但无法解决这个问题:
我想我可能需要一些for循环,但是我被困在这个循环中了!
如果A列中从下到上的总和是28,我想返回总和是28的索引。在本例中,它将是10+7+11 = 28,索引(Date)是5,所以我想返回5。
Date__A
0_____11
1_____9
2_____10
3_____8
4_____2
5_____11
6_____7
7_____10
发布于 2021-11-01 12:42:26
使用以下df:
df = pd.DataFrame({'Date':[0, 1, 2, 3, 4, 5, 6, 7],
'A':[11, 9, 10, 8, 2, 11, 7, 10]})
df = df.set_index('Date')通过颠倒数据帧,您可以找到向后累积总和。然后,您可以反转此列表,并将其作为另一列添加到原始数据帧中:
cumsum = df[::-1].cumsum()['A'].to_list()
cumsum.reverse()
df['cumsum'] = cumsum然后,您可以获得df子集的第一个索引,其中的cumsum为<=28 (如果没有精确地添加到28,这将返回最接近的索引,其中sum < 28 )。
index = df.loc[df['cumsum'] <= 28].first_valid_index()发布于 2021-11-01 12:33:10
使用:
import pandas as pd
# setup
df = pd.DataFrame.from_dict({'Date': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7},
'A': {0: 11, 1: 9, 2: 10, 3: 8, 4: 2, 5: 11, 6: 7, 7: 10}})
res = df.iloc[::-1, 1].cumsum().eq(28).idxmax()
print(res)输出
5发布于 2021-11-01 12:43:51
从计算临时级数开始
wrk = df.set_index('Date').A要计算"wanted“元素的索引,从顶部开始计算,运行:
res = wrk[wrk.cumsum() == 28]
iFirst = res.index[0] if res.size > 0 else np.nan要从底部计算索引计数,也应该从底部计算cummsum:
res = wrk[wrk[::-1].cumsum() == 28]
iLast = res.index[-1] if res.size > 0 else np.nanhttps://stackoverflow.com/questions/69796821
复制相似问题