如何在DataFrame中拼接字符串列A、B与索引生成新列?
Hey there! Creating that combined column is totally straightforward—let me walk you through a couple of reliable methods, using a concrete example to make it clear.
First, let's set up a sample DataFrame so we can test our code:
import pandas as pd # Sample DataFrame with custom index (to show non-default indices work too) df = pd.DataFrame({ 'A': ['apple', 'banana', 'cherry'], 'B': ['red', 'yellow', 'dark red'] }, index=[101, 102, 103])
Our goal is to add a Combined column that looks like apple_red_101, banana_yellow_102, etc.
Method 1: Vectorized String Concatenation (Recommended)
This method is faster for large DataFrames because it uses pandas' built-in vectorized operations instead of looping through rows:
# Convert index to string first (since it's numeric here) and concatenate df['Combined'] = df['A'] + '_' + df['B'] + '_' + df.index.astype(str)
If your index is already a string type (like ['idx1', 'idx2']), you can skip the astype(str) part—just use df.index directly.
Method 2: Using apply for Row-wise Processing
If you need more flexibility (like custom separators or conditional logic later), you can use apply with a lambda function:
# row.name gives us the index value for each row df['Combined'] = df.apply(lambda row: f"{row['A']}_{row['B']}_{row.name}", axis=1)
The axis=1 parameter tells pandas to apply the function to each row instead of each column.
After running either method, your DataFrame will have the new combined column exactly as you want!
内容的提问来源于stack exchange,提问作者Zubo

