我有一个这样的数据框,
df
col1 col2 col3
1 2 3
2 5 6
7 8 9
10 11 12
11 12 13
13 14 15
14 15 16
现在,当两个连续行的col1差大于1时,我想从上方创建多个数据帧。 因此结果数据帧看起来像
df1
col1 col2 col3
1 2 3
2 5 6
df2
col1 col2 col3
7 8 9
df3
col1 col2 col3
10 11 12
11 12 13
df4
col1 col2 col3
13 14 15
14 15 16
我可以使用for循环并存储索引来执行此操作,但这会增加执行时间,寻找一些熊猫快捷方式或pythonic方式来最有效地执行此操作。
答案 0 :(得分:2)
您可以通过获取diff
来定义自定义分组程序,检查其是否大于1
,并获取布尔系列的cumsum
。然后将结果分组并从groupby对象构建字典:
d = dict(tuple(df.groupby(df.col1.diff().gt(1).cumsum())))
print(d[0])
col1 col2 col3
0 1 2 3
1 2 5 6
print(d[1])
col1 col2 col3
2 7 8 9
更详细的细分:
df.assign(difference=(diff:=df.col1.diff()),
condition=(gt1:=diff.gt(1)),
grouper=gt1.cumsum())
col1 col2 col3 difference condition grouper
0 1 2 3 NaN False 0
1 2 5 6 1.0 False 0
2 7 8 9 5.0 True 1
3 10 11 12 3.0 True 2
4 11 12 13 1.0 False 2
5 13 14 15 2.0 True 3
6 14 15 16 1.0 False 3
答案 1 :(得分:0)
您也可以剥离目标列并将其作为系列使用,而不是上面的答案。这样可以使所有内容变小。在该示例上运行速度更快,但是我不知道它们会如何扩展,具体取决于您要拆分多少次。
row_bool = df['col1'].diff()>1
split_inds, = np.where(row_bool)
split_inds = np.insert(arr=split_inds, obj=[0,len(split_inds)], values=[0,len(df)])
df_tup = ()
for n in range(0,len(split_inds)-1):
tempdf = df.iloc[split_inds[n]:split_inds[n+1],:]
df_tup.append(tempdf)
(只是将其扔入一个数据帧的元组中,但是使用字典方法可能更好?)