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

Pandas如何向列中追加数据?实现列内容带括号拼接

Pandas实现列内容带括号追加

不用写循环,直接用Pandas的字符串操作就能搞定,两种常用方法:

方法一:向量化字符串拼接(推荐,速度更快)

直接对列进行字符串拼接操作,先把数值类型的col2转为字符串,再和col1按格式组合:

import pandas as pd

# 初始化数据
df = pd.DataFrame({'col1': ['A', 'B'], 'col2': [1, 2]})

# 执行拼接
df['col1'] = df['col1'] + ' (' + df['col2'].astype(str) + ')'

方法二:apply函数灵活拼接

如果需要更复杂的格式,可以用apply结合lambda表达式:

df['col1'] = df.apply(lambda row: f"{row['col1']} ({row['col2']})", axis=1)

两种方法执行后,都会得到你想要的结果:

col1col2
A (1)1
B (2)2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:15:29