累积总和并在python中分解为不同的数据帧? [英] cumulative sum and breaking into different data frames in python?

查看:65
本文介绍了累积总和并在python中分解为不同的数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python DataFrame

Col A = 0.5, 0.3,1 , 3 , 0.2 , 3, 3, 4, 5

,我有一个固定值,即dis = 4 我必须取出列A的总和,如果该总和是greater than the dis分开的那些行,并以相同的方式开始,直到最后五行结束,例如前五行总和大于dis,我将其分解为不同的DataFrame,然后我接下来的几行总和为== dis,我可以将其分解为不同的DataFrame,直到最终处理完所有行为止,我知道for循环是可行的方法,但是有更好的解决方案吗?

and I have one fixed value which is dis = 4 I have to take out sum, of col A, if that sum is greater than the dis separate those rows, and start the same thing where it ends last like first five rows sum is greater than dis, I break it in different DataFrame, then I have next few rows sum which is == dis and I can break it into different DataFrame until it ends up doing all rows, I know for loop is possible way to do it, but any better solution?

可以在Python中做吗?

Is it possible to do in Python?

推荐答案

让我们执行以下操作:

A=[]
m=0
for y,x in enumerate(df.Col1):
    m+=x
    print(m)
    if m>=4:
        m=0
        A.append(y)
    else:
        m=m

df['g']=np.nan
df.g.iloc[A]=list(range(len(A)))
df=df.bfill()

现在您有了新的g列,则可以拆分df

Now you have new column g, then you can split the df

[y for _,y in df.groupby('g')]
Out[965]: 
[   Col1    g
 0   0.5  0.0
 1   0.3  0.0
 2   1.0  0.0
 3   3.0  0.0,    Col1    g
 4   0.2  1.0
 5   3.0  1.0
 6   3.0  1.0,    Col1    g
 7   4.0  2.0,    Col1    g
 8   5.0  3.0]

这篇关于累积总和并在python中分解为不同的数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆