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

如何在Pandas中同时拆分DataFrame列并为拆分后的新列重命名?

Solution for Splitting and Renaming Column in One Line

Got it, let's get this sorted for you! The problem with your existing code is that you're splitting the column and renaming the resulting DataFrame, but you aren't merging those new columns back into your original thyroid_df. Here's the one-liner that handles splitting, renaming, and integrating the new columns all in a single step:

thyroid_df = thyroid_df.join(thyroid_df.pop(0).str.split(':', expand=True).rename(columns={0: "CHROM", 1: "POS_GRCh38", 2: "REF", 3: "Effect_allele"}))

Quick breakdown of what this does:

  • thyroid_df.pop(0): Removes the original column 0 from your DataFrame and returns it, so we can manipulate it without leaving the original column hanging around.
  • str.split(':', expand=True): Splits each string in the column on every colon, and converts the split results into a new DataFrame. Since your entries have exactly 4 segments separated by colons, we don't need to specify the n parameter here—it'll split perfectly into 4 columns.
  • rename(columns={0: "CHROM", 1: "POS_GRCh38", 2: "REF", 3: "Effect_allele"}): Renames the default numeric column names (0,1,2,3) to your desired descriptive names.
  • join(): Adds the newly split and renamed columns back to your original DataFrame, giving you the final structure you want.

After running this line, your thyroid_df will have the new columns CHROM, POS_GRCh38, REF, Effect_allele instead of the original column 0, plus your existing columns 1 and 2.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:02:40