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

Pandas添加DataFrame列时出现偏移问题求助

问题描述

尝试用Pandas处理含5层嵌套索引的大型数据集以计算ANOVA,原DataFrame dSchema 结构如下:

X  q  c  s  r  i
1     3.0  0  0  0  0  0
2     3.0  0  0  0  0  1
3     3.0  0  0  0  0  2
4     3.0  0  0  0  0  3
5     3.0  0  0  0  0  4
...   ... .. .. .. .. ..
8496  1.0  8  4  9  1  0
8497  0.0  8  4  9  1  1
8498  0.0  8  4  9  1  2
8499  0.0  8  4  9  1  3
8500  0.0  8  4  9  1  4

[8500 rows x 6 columns]

为计算需求生成的filter列数据框:

filter
0     ['0', '0', '0']
1     ['0', '0', '1']
2     ['0', '0', '2']
3     ['0', '0', '3']
4     ['0', '0', '4']
...               ...
8495  ['8', '9', '0']
8496  ['8', '9', '1']
8497  ['8', '9', '2']
8498  ['8', '9', '3']
8499  ['8', '9', '4']

[8500 rows x 1 columns]

将filter列添加至原DataFrame后出现错位,最后一行显示<NA>:

X  q  c  s  r  i           filter
1     3.0  0  0  0  0  0  ['0', '0', '1']
2     3.0  0  0  0  0  1  ['0', '0', '2']
3     3.0  0  0  0  0  2  ['0', '0', '3']
4     3.0  0  0  0  0  3  ['0', '0', '4']
5     3.0  0  0  0  0  4  ['0', '0', '0']
...   ... .. .. .. .. ..              ...
8496  1.0  8  4  9  1  0  ['8', '9', '1']
8497  0.0  8  4  9  1  1  ['8', '9', '2']
8498  0.0  8  4  9  1  2  ['8', '9', '3']
8499  0.0  8  4  9  1  3  ['8', '9', '4']
8500  0.0  8  4  9  1  4             <NA>

[8500 rows x 7 columns]
原因分析

核心问题是两个数据框的索引不匹配:

  • 原dSchema的索引范围是1~8500
  • filter数据框的索引范围是0~8499

Pandas合并列时默认按索引对齐,filter的索引0找不到对应的dSchema索引0,只能从dSchema的索引1开始匹配filter的索引1,最终导致整体错位,且dSchema最后一行索引8500无对应filter索引,显示为<NA>。

解决方法

提供三种直接可行的方案:

方案一:统一两个数据框的索引

将filter数据框的索引修改为和dSchema完全一致:

# 替换filter的索引为dSchema的索引
filter_df.index = dSchema.index
# 添加filter列
dSchema['filter'] = filter_df['filter']

方案二:按位置拼接,忽略索引

使用pd.concat重置索引后按列拼接:

import pandas as pd
dSchema = pd.concat([dSchema, filter_df.reset_index(drop=True)], axis=1)

方案三:直接赋值列的底层数据

忽略索引,直接将filter列的数值数组赋值给新列:

dSchema['filter'] = filter_df['filter'].values

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:53:11