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

如何逐行拆分DataFrame的x/y列并生成指定列的新DataFrame

问题解决:拆分DataFrame数组列并生成目标结构DataFrame

我需要逐行遍历outlierdataframe,拆分其中x和y列的数组值,将每一行拆分后的结果保存为包含newID、x、y列的独立DataFrame。但当前代码运行后所有内容都输出在同一列,无法实现拆分后的x、y值分属不同列,求解决。

原代码

individualframe = outlierdataframe.iloc[0]
individualoutliers = individualframe.explode(list('xy'))
newframe = pd.DataFrame(individualoutliers)
print(newframe)

输入数据(outlierdataframe首行)

index                                                      24
subID                                         Prolific_610020
level                                                       1
complete                                                False
duration                                            20.015686
map_view                                            12.299759
distance                                           203.426697
x           [55, 55, 55, 60, 60, 60, 65, 70, 70, 75, 80, 8...
y           [60, 60, 60, 60, 65, 65, 70, 70, 75, 75, 80, 8...
r           [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1...
batch                                                       1
newID                                                  610020
Name: 24, dtype: object

当前错误输出

24
0                 24
1    Prolific_610020
2                  1
3              False
4          20.015686
..               ...
121               55
122               55
123               55
124                1
125           610020

解决方案

问题根源

原代码对整行Series执行了explode操作,导致所有列(包括非数组类型的列)都被强制展开,最终变成了单列的长格式数据,完全偏离了需求。我们只需要针对x、y两个数组列做展开,同时让对应的newID值重复匹配每一组拆分后的x、y。

修正代码(两种方式)

方式1:直接构造新DataFrame

# 提取目标行数据
target_row = outlierdataframe.iloc[0]
# 基于x、y数组长度重复newID,构造目标结构DataFrame
newframe = pd.DataFrame({
    'newID': [target_row['newID']] * len(target_row['x']),
    'x': target_row['x'],
    'y': target_row['y']
})
print(newframe)

方式2:利用DataFrame的explode方法(更简洁)

# 筛选需要的列并转为单行DataFrame(避免操作Series)
single_row_df = outlierdataframe[['newID', 'x', 'y']].iloc[[0]]
# 对x、y列执行explode,自动关联newID
newframe = single_row_df.explode(['x', 'y'])
print(newframe)

预期输出示例

newID   x   y
0   610020  55  60
0   610020  55  60
0   610020  55  60
0   610020  60  60
...     ...  ..  ..

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:55:27