【问题标题】:iterate over specific column up to a certain value in pandas在熊猫中迭代特定列直到某个值
【发布时间】:2021-10-17 11:42:43
【问题描述】:
A = pd.DataFrame({"type":['a','b','c', 'd','e'], "cost basis":[50, 40, 30, 20, 10], "value":[5, 25, 40, 10, 20]})

我希望将“值”列迭代到某个值或按降序求和。假设是 50,而如果下一个数字超过该值,则迭代将停在那里。

【问题讨论】:

  • 给定数据框的预期输出是什么?
  • 对于这个例子,我们只说 50。因此,按降序迭代 value 列直到 50,然后数据帧中达到该值的每一行都将被添加到一个新的数据帧中。这是针对我正在从事的一个会计项目的,因此我正在过滤数据集以出售特定的税收批次。

标签: python pandas dataframe sum iteration


【解决方案1】:

不确定你想要什么,但如果我理解正确的话:

通过cumsum()尝试:

out=A.loc[A['value'].cumsum().le(50)]

如果要按降序排列,请使用sort_values()+cumsum():

out=A.loc[A.sort_values('value',ascending=False,ignore_index=True)['value'].cumsum().le(50)]

【讨论】:

    【解决方案2】:

    您可以使用两个函数来实现这一点:cumsumargmax

    import numpy as np
    import pandas as pd
    A = pd.DataFrame({"type":['a','b','c', 'd','e'], "cost basis":[50, 40, 30, 20, 10], "value":[5, 25, 40, 10, 20]})
    
    # Cummulated sum of array A
    acumsum = np.cumsum(A.value.values)
    
    # Determine the first index where the value is greater than 50:
    idx = np.argmax(acumsum > 50)
    
    print(idx)
    

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2022-09-23
      • 2020-11-13
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多