如何解决根据条件创建累积列pandas python
我有多列的数据框。其中之一是累积生产。需要创建另一个名为“更正累积列”的列。请检查以下。
df:
我的方法:
我尝试使用前向填充来填充 0,但如果该列具有多组值(例如下面部分中的 100,200,300),则会失败。有没有办法解决这个问题?
import pandas as pd
data = {'CummulativeProdution':[100,300,100,0]
}
df = pd.DataFrame(data)
解决方法
您可能需要从第一个零之前的值开始运行 cumsum():
df['Corrected'] = df['CummulativeProdution']
mask = df['CummulativeProdution'] == 0
# if the series has zeros
if mask.any():
# find the index of the first zero
first_zero_idx = df[mask].index[0]
# assuming monotonic increasing index
before_zero_idx = first_zero_idx - 1
df.loc[before_zero_idx:,'Corrected'] = df.loc[before_zero_idx:,'Corrected'].cumsum()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。