【问题标题】:How to sum values in pandas based on bool condition如何根据布尔条件对熊猫中的值求和
【发布时间】:2020-07-30 02:15:22
【问题描述】:

我有以下数据框:

                   High          Low  ...    Adj Close    bcc
Date                                  ...                    
2018-01-02  2695.889893  2682.360107  ...  2695.810059  False
2018-01-03  2714.370117  2697.770020  ...  2713.060059  False
2018-01-04  2729.290039  2719.070068  ...  2723.989990  False
2018-01-05  2743.449951  2727.919922  ...  2743.149902  False
2018-01-08  2748.510010  2737.600098  ...  2747.709961   True
                ...          ...  ...          ...    ...
2020-04-09  2818.570068  2762.360107  ...  2789.820068  False
2020-04-13  2782.459961  2721.169922  ...  2761.629883  False
2020-04-14  2851.850098  2805.100098  ...  2846.060059  False
2020-04-15  2801.879883  2761.540039  ...  2783.360107  False
2020-04-16  2806.510010  2764.320068  ...  2778.219971  False

每当密件抄送列是 True 时,我如何添加列 Low 的下 3 个值并将这些数据保存到不同的数据框中?

【问题讨论】:

  • 你先过滤,所以df.iloc[df['bcc'], 'Low'].sum()
  • 看起来这里已经有了答案stackoverflow.com/questions/37947641/…
  • @WillemVanOnsem 你的意思是df.iloc[df['bcc'], 'Low'].sum(3) ?
  • @WillemVanOnsem 我得到了ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
  • @WillemVanOnsem df.loc[df['bcc'], 'Low'].sum(),而不是 iloc。但我认为这不是 OP 需要的,因为它无法处理 next 3 values

标签: python-3.x pandas boolean


【解决方案1】:

我不确定这段代码的效率,但你可以试试这个:

match_idx = df.index[df.bcc == True].tolist()

next_three_rows_list = [list(range(idx+1,idx+4)) for idx in match_idx]
sums = []
for i in range(0,len(next_three_rows)):
    sums.append(df.loc[next_three_rows[i]].Low.sum())

new_df = pd.DataFrame(sums,columns=['sum'])

【讨论】:

  • 感谢您的帮助。当我 next_three_rows_list = [list(range(idx+1,idx+4)) for idx in match_idx] 我得到一个 ValueError ValueError: Cannot add integral value to Timestamp without freq 我如何指定频率?
  • ValueError 即将出现,因为您将 Date 作为索引。尝试在match_idx = df.index[df.bcc == True].tolist() 之前使用df.index.rename('Date',inplace=True)df = df.reset_index() 重置索引。这会将数据框的索引重置为整数。
  • 我完全按照你说的做了,但是当我做df.dtypes时我得到了Date datetime64[ns]
  • 重置后没有改变dtype。并得到同样的错误
  • 重启内核后它工作了!感谢您的帮助。我需要思考的部分代码
猜你喜欢
  • 2021-05-24
  • 2020-06-21
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 2022-01-04
  • 2022-01-15
  • 2022-01-25
  • 2021-08-27
相关资源
最近更新 更多