我在一个数据帧中有数千行数据,如下所示:
我想要只提取存在于以下输出的从平台的每个开始("Type"列)到平台("Frame"列)的每个结束("Type"列)的所有数据行,并将CLASS列中的数据命名为P1(第一个平台开始和平台结束内的所有行)、P2(第二个平台开始和结束)、P3、P4等:
我在一个数据帧中有数千行数据,如下所示:
我想要只提取存在于以下输出的从平台的每个开始("Type"列)到平台("Frame"列)的每个结束("Type"列)的所有数据行,并将CLASS列中的数据命名为P1(第一个平台开始和平台结束内的所有行)、P2(第二个平台开始和结束)、P3、P4等:
欢迎来到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