python - 从 pandas df 中选择并计算特定值
问题描述
我需要一些帮助来解决以下问题:
数据看起来像
dt value
15 0
15 2
15 8
15 8
15 10
16 12
15 19
15 35
15 45
16 45
16 45
15 50
15 0
16 26
15 43
15 50
15 0
.
.
.
现在我必须总结 dt 直到值达到 50,总是从 0 开始。
我尝试了以下方法,但我不确定它是否正确,
df['value'].values[(df['value'].values > 0) & (df['value'].values < 50)] = 1
df = df.assign(counter_col_x = df.loc[df['value'].eq(1)].groupby(df['value'].ne(df['value'].shift()).cumsum()).ngroup())
感谢您的任何提示!
解决方案
如果您不必在一个列中重新启动多次,一种简单的方法是对一个系列进行累积总和。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html
我希望您的意思是值的累积总和,直到达到 50。我只能想出一种在循环中分配 Series 值的方法。希望有帮助。
new_cum_sum = 0
list_of_values = []
for x, y in zip(test['dt'], test['value']):
if y== 0:
new_cum_sum = x
elif y <= 50:
new_cum_sum+=x
list_of_values.append(new_cum_sum)
test['test_cum'] = list_of_values
推荐阅读
- azure - Azure 逻辑应用,队列中没有内容
- python - Django order_by 两个字段,第一个字段最后为空
- c++ - 在 GCC-7 中使用功能测试宏
- javascript - React:渲染大图像和放大
- javascript - Java Script Function 对于特定的正则表达式运行良好,但在另一个正则表达式中无法正常运行
- c# - 使用查找集合的 IValueConverter
- c# - Azure 函数 httpclient ObjectDisposedException 无法访问已处置的对象 SslStream
- excel - 无法工作簿。打开 XLS 文件类型?
- google-sheets - 如何创建一个公式来对一列中的值求和,但将这些值乘以另一列?
- c# - 如何将此解密合并到我的代码中,将散列密码转换回原始密码