我有一个警察的办公室:

import pandas as pd
column1 = [None,None,None,4,8,9,None,None,None,2,3,5,None]
column2 = [None,None,None,None,5,1,None,None,6,3,3,None,None]
column3 = [None,None,None,3,None,7,None,None,7,None,None,1,None]
df = pd.DataFrame(np.column_stack([column1, column2,column3]),columns=['column1', 'column2', 'column3'])

print(df)
   column1 column2 column3
0     None    None    None
1     None    None    None
2     None    None    None
3        4    None       3
4        8       5    None
5        9       1       7
6     None    None    None
7     None    None    None
8     None       6       7
9        2       3    None
10       3       3    None
11       5    None       1
12    None    None    None

我希望将第3列中的值之间的行设为子集,并删除所有空行.我想要的结果是:

print (df1)   
   column1 column2 column3
0        4    None       3
1        8       5    None
2        9       1       7

print(df2)
   column1 column2 column3
0     None       6       7
1        2       3    None
2        3       3    None
3        5    None       1

我不关心实际值列3.第3列的值用于指示"开始"和"停止".

推荐答案

You can find the non-na value, then perform a cumulative sum, then mod 2 to get the "groups" of start and one-less-than stop positions. Shifting this by 1, adding to the original, and clipping to (0, 1) gets clumps of the start and stop points.
To label the groups, you can take a diff of 1, then clip to (0, 1) again, and cum sum, then multiply those two together.

g_small = (~df.column3.isna()).cumsum().mod(2)
g = (g_small  + g_small .shift(1, fill_value=0)).clip(0,1)

groups = g.diff(1).fillna(0).clip(0,1).cumsum().astype(int) * g

然后,您可以对数据帧执行groupby操作:

dfs = {i: g for i, g in df.groupby(groups) if i > 0}

dfs
# returns:
{1:
   column1 column2 column3
 3       4    None       3
 4       8       5    None
 5       9       1       7,

 2:
    column1 column2 column3
 8     None       6       7
 9        2       3    None
 10       3       3    None
 11       5    None       1}

Python相关问答推荐

比较两个数据帧并并排附加结果(获取性能警告)

使用miniconda创建环境的问题

运行Python脚本时,用作命令行参数的SON文本

在线条上绘制表面

Polars:用氨纶的其他部分替换氨纶的部分

基于字符串匹配条件合并两个帧

不允许访问非IPM文件夹

UNIQUE约束失败:customuser. username

Flask Jinja2如果语句总是计算为false&

如何找出Pandas 图中的连续空值(NaN)?

导入错误:无法导入名称';操作';

OpenGL仅渲染第二个三角形,第一个三角形不可见

Pandas—MultiIndex Resample—我不想丢失其他索引的信息´

如何获得3D点的平移和旋转,给定的点已经旋转?

使用SQLAlchemy从多线程Python应用程序在postgr中插入多行的最佳方法是什么?'

多个矩阵的张量积

如何为需要初始化的具体类实现依赖反转和接口分离?

Pandas:将值从一列移动到适当的列

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)

将索引表转换为Numy数组