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

如何在DataFrame中拼接字符串列A、B与索引生成新列?

How to Create a New Column by Combining Columns A, B, and the DataFrame Index

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.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:03:56