使用itertuples()和列值条件在数据帧上迭代

2024-04-20 09:49:30 发布

您现在位置:Python中文网/ 问答频道 /正文

每次x<;=20时,我都尝试在数据帧中选择一个范围,并使用列创建一个新的数据帧,列是该范围内所选行(包括负值)的总和,并保留最后一个日期作为索引。如果我在正确的道路上 这是我想要的输出,低于我的方法,这是行不通的。你知道吗

Date         x             Date         sum
2019-01-01   100           2019-01-05   343
2019-01-02   120   --->    2019-01-10   804
2019-01-03    80           2019-01-15   650
2019-01-04    48           2019-01-20   428
2019-01-05     5           ...
2019-01-06   110           ...
2019-01-07   420
2019-01-08   140
2019-01-09   126
2019-01-10     8
2019-01-11    50
2019-01-12   160   
2019-01-13   280
2019-01-14   148
2019-01-15    12
2019-01-16   190
2019-01-17   120
2019-01-18    80
2019-01-19    48
2019-01-20   -10
...
...

#######
for date in df.index.to_series().dt.date.unique():
   for row in df.itertuples():
      for i in row:
         if i <= 20:
           new_df = pd.DataFrame(columns=df.keys())
           new_df.index.name = 'Date'
           new_df ['sum'] = df.sum(axis = 0)
         continue:
#

Tags: 数据inltdfnewfordateindex
1条回答
网友
1楼 · 发布于 2024-04-20 09:49:30

为什么不使用groupby?你知道吗

df.groupby(df['x'].shift().le(20).cumsum()) \
  .agg(Date=('Date','last'), sum = ('x','sum')).set_index('Date')

            sum
Date           
2019-01-05  353
2019-01-10  804
2019-01-15  650
2019-01-20  428

相关问题 更多 >