我在一个数据帧中有数千行数据,如下所示:

input table

我想要只提取存在于以下输出的从平台的每个开始("Type"列)到平台("Frame"列)的每个结束("Type"列)的所有数据行,并将CLASS列中的数据命名为P1(第一个平台开始和平台结束内的所有行)、P2(第二个平台开始和结束)、P3、P4等:

Output table

推荐答案

欢迎来到Stack Overflow!

这是我会怎么做的.这可能不是最干净的解决方案,但我认为它能做你想做的事情.

# Set up reproductible example (reprex)
import pandas as pd

df = pd.DataFrame({
    "Frame": ["liner", "platform", "liner", "liner", "platform",
              "liner", "platform", "liner", "platform", "liner"],
    "Type": ["group", "start", "single", "single", "end",
             "single", "start", "group", "end", "single"]
})

#    Frame       Type
# 0  liner       group
# 1  plateform   start
# 2  liner       single
# 3  liner       single
# 4  plateform   end
# 5  liner       single
# 6  plateform   start
# 7  liner       group
# 8  plateform   end
# 9  liner       single

步骤1:从平台的开始到结束 Select 行

start_indices = df.index[(df.Frame == "platform") & (df.Type == "start")]
end_indices = df.index[(df.Frame == "platform") & (df.Type == "end")]

df = pd.concat([
    df[start:end+1] for start, end in zip(start_indices, end_indices)
])

第二步:增加站台号栏目

df["Class"] = (
    pd.Series(
        [f"P{n}" for n in  range(1, len(start_indices) + 1)],
        index=start_indices
    )
    .reindex(df.index)
    .fillna(method="ffill")
)

这就是你能得到的:

df

#    Frame      Type    Class
# 1  platform   start   P1
# 2  liner      single  P1
# 3  liner      single  P1
# 4  platform   end     P1
# 6  platform   start   P2
# 7  liner      group   P2
# 8  platform   end     P2

Python相关问答推荐

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

将jit与numpy linSpace函数一起使用时出错

如何在Windows上用Python提取名称中带有逗号的文件?

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

如何请求使用Python将文件下载到带有登录名的门户网站?

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

关于Python异步编程的问题和使用await/await def关键字

在极性中创建条件累积和

给定高度约束的旋转角解析求解

将JSON对象转换为Dataframe

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

Python避免mypy在相互引用中从另一个类重定义类时失败

如何将数据帧中的timedelta转换为datetime

polars:有效的方法来应用函数过滤列的字符串

如何在一组行中找到循环?

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

将字节序列解码为Unicode字符串

查找查找表中存在的列值组合

极点:在固定点扩展窗口

如何将参数名作为参数传入到函数中?