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

如何在Pandas DataFrame元素中拆分字符串并重组列表片段

Solution to Rejoin First Three Split String Parts in Pandas

You're on the right track with splitting the strings—now let's adjust your code to efficiently rejoin the first three segments directly in Pandas without messy loops or workarounds.

Method 1: Pandas String Methods (Most Efficient)

Pandas' str accessor plays nicely with list-like results from str.split(), so you can slice the list and rejoin it in one concise line:

import pandas as pd

df = pd.DataFrame({'code': ['PC001-S002_D_CFI4-1_NN','PC001-S002_D_CFI4-1_NN','PC001-S002_D_CFI4-1_NN', 'PC001-S002_D_CFI4-1_ER','PC001-S002_D_CFI4-1_ER','PC001-S002_D_CFI4-1_ER']})

# Split by underscore, take first 3 elements, rejoin with underscore
df['domain'] = df['code'].str.split("_").str[:3].str.join("_")

print(df)

This will give you exactly the output you want: each domain value will be the first three parts of the code string joined back together with underscores.

Method 2: Expand Split into Columns (Explicit & Readable)

If you prefer a more straightforward approach for clarity, you can expand the split into separate columns, then concatenate the first three:

# Split the code column into individual columns
split_columns = df['code'].str.split("_", expand=True)

# Join the first three columns with underscores
df['domain'] = split_columns[0] + "_" + split_columns[1] + "_" + split_columns[2]

This works great if you know the number of segments is consistent, and it’s easy to follow for anyone new to Pandas string operations.

Method 3: Adapt Your Original Logic with apply

If you wanted to reuse your single-string processing code, you can wrap it in a lambda function with apply:

df['domain'] = df['code'].apply(lambda x: "_".join(x.split("_")[:3]))

Note: This method works but is less efficient for large DataFrames since it operates row-by-row instead of using Pandas' vectorized operations.

All three methods will produce the same result:

codedomain
PC001-S002_D_CFI4-1_NNPC001-S002_D_CFI4-1
PC001-S002_D_CFI4-1_NNPC001-S002_D_CFI4-1
PC001-S002_D_CFI4-1_ERPC001-S002_D_CFI4-1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:41:53