我有一个日期和值的数据框。即
index | date | points
0 | 9-15-17 | 10.2
1 | 9-15-17 | 5.0
2 | 9-15-17 | -3.0
3 | 9-15-17 | -1.6
4 | 9-15-17 | 3.8
5 | 9-15-17 | 7.0
6 | 9-15-17 | 4.6
有没有办法利用pandas中的groupby将数据框折叠成
index | date | points
0 | 9-15-17 | 15.2
1 | 9-15-17 | -4.6
2 | 9-15-17 | 15.4
我当前正在发送日期列,并指向列表并使用多个循环来检查值(数据帧是 C_list)
net_score = 0
rolling_score = []
print(type(int(C_list[0])))
for i in range(0,len(C_list)):
if C_list[i] > 0:
if(net_score + C_list[i] > net_score):
net_score += C_list[i]
else:
rolling_score.append(net_score)
net_score = 0
net_score += C_list[i]
if C_list[i] < 0:
if(net_score + C_list[i] < net_score):
net_score += C_list[i]
else:
rolling_inv.append(net_inv)
net_inv = 0
net_inv += C_list[i]
由于某种原因,我得到了一个这样的列表:[15.2,-3.0],因此当我由于某种原因达到负点时,它会停止添加值。我意识到在数据框中可能有一种更简单的方法来做到这一点,但我很难理解如何正确利用 pandas 来做到这一点。与其说是在寻找完整的代码,不如说是在寻找一些关于这是否可以在数据框中轻松完成的见解,以及建议使用的函数是什么。
最佳答案
m=df['points'].lt(0).ne(df['points'].lt(0).shift()).cumsum()
df1= df.groupby([m,'date']).sum().drop(columns=['index'])
df1.index = df1.index.droplevel(0)
df1.reset_index(inplace=True)
print(df1)
输出
date points
0 9-15-17 15.2
1 9-15-17 -4.6
2 9-15-17 15.4
关于python - 有没有办法根据同一列中值的参数折叠数据框列中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57918455/