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

如何将Pandas DataFrame的index列按逗号拆分为两列

解决方法

pd.explode()的作用是将单元格内的可迭代对象拆分为多行,显然不符合你拆分列的需求。针对你的场景,分两种情况处理:

场景1:index列存储的是元组类型

如果你的index列是Python元组(比如(DAL, AAL)是实际的元组对象),可以直接用apply(pd.Series)拆分出两列,再与原数据合并:

# 拆分元组为两列
split_index = data_combined['index'].apply(pd.Series)
split_index.columns = ['index1', 'index2']

# 合并并移除原index列
final_df = pd.concat([split_index, data_combined.drop('index', axis=1)], axis=1)

场景2:index列是带括号的字符串类型

如果index列是字符串格式(比如"(DAL, AAL)"),需要先清理字符串再拆分:

# 去除首尾括号,按逗号+空格拆分,生成新列
split_index = data_combined['index'].str.strip('()').str.split(', ', expand=True)
split_index.columns = ['index1', 'index2']

# 合并数据
final_df = pd.concat([split_index, data_combined.drop('index', axis=1)], axis=1)

最终效果

运行后得到的final_df结构如下:

index1 index2  corr_year  corr_5d
0     DAL    AAL   0.873762  0.778594
1     WEC     ED   0.851578  0.850549
2     CMS    LNT   0.850028  0.776143
3    SWKS   QRVO   0.850799  0.830603
4     ALK    DAL   0.874162  0.744590

额外说明

  • str.split(expand=True)是处理字符串拆分的高效方法,直接返回DataFrame,无需额外转换;
  • 若不确定index列的类型,可以用type(data_combined['index'].iloc[0])查看。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:15:35