You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将嵌套数据对拆分至多列?

Pandas嵌套IN/OUT数据对转多列的解决方案

观察数据和期望输出,IN序列需要与逆序后的OUT序列一一配对,可通过以下Pandas步骤实现:

实现步骤

  1. 分离IN/OUT数据:筛选出action为IN和OUT的行,分别提取时间戳列
  2. 反转OUT序列:按期望的配对逻辑,将OUT的时间戳序列反转,确保第一个IN对应最后一个OUT
  3. 合并为目标DataFrame:将处理后的IN、OUT序列合并,设置对应列名

完整代码示例

import pandas as pd

data = [
 [1,'IN'],
 [2,'IN'],
 [3,'OUT'],
 [4,'OUT'],
 [5,'IN'],
 [6,'IN'],
 [7,'OUT'],
 [8,'OUT']
]
df = pd.DataFrame(data, columns=['ts','action'])

# 分离IN和OUT数据
in_data = df[df['action'] == 'IN'].copy()
out_data = df[df['action'] == 'OUT'].copy()

# 反转OUT序列并重置索引,保证与IN序列对齐
out_data_reversed = out_data.iloc[::-1].reset_index(drop=True)

# 合并生成结果
result = pd.concat([
    in_data['ts'].rename('ts_IN'),
    out_data_reversed['ts'].rename('ts_OUT')
], axis=1)

print(result)

运行后输出与期望一致:

ts_IN  ts_OUT
0      1       4
1      2       3
4      5       8
5      6       7

分组适配方案(适用于分组规则明确的场景)

如果数据中每组IN/OUT的数量固定(如每组2个IN对应2个OUT),可通过分组编号的方式处理,逻辑更清晰:

import pandas as pd

data = [
 [1,'IN'],
 [2,'IN'],
 [3,'OUT'],
 [4,'OUT'],
 [5,'IN'],
 [6,'IN'],
 [7,'OUT'],
 [8,'OUT']
]
df = pd.DataFrame(data, columns=['ts','action'])

# 为连续相同的action分组编号
df['group'] = (df['action'] != df['action'].shift()).cumsum()

# 提取IN分组的时间戳并展开
in_groups = df[df['action'] == 'IN'].groupby('group')['ts'].apply(list).explode().reset_index()
# 提取OUT分组的时间戳,反转每组内的顺序后展开
out_groups = df[df['action'] == 'OUT'].groupby('group')['ts'].apply(lambda x: list(reversed(x))).explode().reset_index()

# 合并并保留原IN的索引
result = pd.concat([
    in_groups['ts'].rename('ts_IN'),
    out_groups['ts'].rename('ts_OUT')
], axis=1)
result.index = in_groups['index']

print(result)

内容的提问来源于stack exchange,提问作者lucky1928

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:20:07