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

Python pandas如何创建值为count(percent)格式的合并值新列

Pandas拼接计数和百分比列实现方案

你可以通过以下两种常用方法完成列拼接需求:

方法1:直接字符串拼接(性能更高,适合大数据量场景)

直接将两列转为字符串类型后拼接,代码如下:

import pandas as pd

# 示例数据
df = pd.DataFrame({'count': [1,2,3],
                   'percent': [30,35,35]})

# 新增拼接列
df['count(percent)'] = df['count'].astype(str) + '(' + df['percent'].astype(str) + ')'

print(df)

运行后即可得到你需要的输出结果。

方法2:apply + f-string(写法更灵活,适合需要复杂格式调整的场景)

如果后续需要调整拼接格式(比如给百分比加%后缀、保留指定小数位),用lambda加f-string的方式调整更方便:

import pandas as pd

df = pd.DataFrame({'count': [1,2,3],
                   'percent': [30,35,35]})

# 新增拼接列
df['count(percent)'] = df.apply(lambda row: f"{row['count']}({row['percent']})", axis=1)

print(df)

如果你的percent字段是0.3这类小数格式,想要展示为1(30%)的效果,只需要修改f-string格式即可:

df['count(percent)'] = df.apply(lambda row: f"{row['count']}({row['percent']:.0f}%)", axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 17:36:08