如何根据列中值的差异拆分 pandas 数据框 [英] How to split pandas dataframe based on difference of values in a column
问题描述
我有一个熊猫数据框,其中有几列,称为 strike。如果strike列的行的值大于100加上strike列的前一行,我想将数据框分为两部分到那时(它们仍然具有相同的列名),依此类推。我对pandas很陌生,在查找了一些功能之后找不到一种简单的方法。
I have a pandas dataframe with a few columns, one called 'strike.' If the value of a row of the strike column is greater than 100 plus the previous row of the strike column, I want to split the dataframe into two at that point (they'd still have the same column names) and so on. I'm quite new at pandas and couldn't figure out a simple way to do this after looking up some functions.
示例:以下数据框:
strike crv vol
1400 w a
1450 x b
1600 y c
1800 z d
将会是3个数据帧:
strike crv vol
1400 w a
1450 x b
strike crv vol
1600 y c
strike crv vol
1800 z d
谢谢!
推荐答案
IIUC,这是compare-cumsum-groupby模式的另一个示例:
IIUC, this is yet another example of the compare-cumsum-groupby pattern:
>>> df
strike crv vol
0 1400 w a
1 1450 x b
2 1600 y c
3 1800 z d
>>> group_ids = (df["strike"] > (df["strike"].shift() + 100)).cumsum()
>>> grouped = df.groupby(group_ids)
>>> for k,g in grouped:
... print("-----")
... print(g)
...
-----
strike crv vol
0 1400 w a
1 1450 x b
-----
strike crv vol
2 1600 y c
-----
strike crv vol
3 1800 z d
您可以如果愿意,可以将其放入列表或字典中。
And you can put this into a list or dictionary if you'd like:
>>> group_list = [g for k,g in grouped]
>>> group_list[2]
strike crv vol
3 1800 z d
>>> group_dict = dict(list(grouped))
>>> group_dict[1]
strike crv vol
2 1600 y c
之所以有用,是因为我们利用True == 1和False == 0的事实来构建组ID:
This works because we build the group ids taking advantage of the fact that True == 1 and False == 0:
>>> df["strike"] > (df["strike"].shift() + 100)
0 False
1 False
2 True
3 True
Name: strike, dtype: bool
>>> (df["strike"] > (df["strike"].shift() + 100)).cumsum()
0 0
1 0
2 1
3 2
Name: strike, dtype: int64
然后我们可以将这些值分组
and we can then group on these values.
这篇关于如何根据列中值的差异拆分 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!