如何在Pandas DataFrame元素中拆分字符串并重组列表片段
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:
| code | domain |
|---|---|
| PC001-S002_D_CFI4-1_NN | PC001-S002_D_CFI4-1 |
| PC001-S002_D_CFI4-1_NN | PC001-S002_D_CFI4-1 |
| PC001-S002_D_CFI4-1_ER | PC001-S002_D_CFI4-1 |
内容的提问来源于stack exchange,提问作者BillyJo_rambler

