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

如何使用string.format()方法将Pandas DataFrame数据传入字符串

没问题,我来帮你搞定这个需求!你需要把DataFrame里的每一行数据对应填入format()的占位符中,这里有几种实用的方法:

方法1:遍历每一行生成消息(适合小数据集)

你可以用iterrows()遍历DataFrame的每一行,然后把每行的姓名、年龄、分数依次传入format():

import pandas as pd
df = pd.read_csv('data.csv')
message = "{} is {} years old and has a score of {}"

# 遍历并生成每条消息
for _, row in df.iterrows():
    # 按顺序传入A列(姓名)、B列(年龄)、C列(分数)
    formatted_msg = message.format(row['A'], row['B'], row['C'])
    print(formatted_msg)

运行后会输出:

Matt is 23 years old and has a score of 0.98
Mark is 34 years old and has a score of 9.33
Luke is 52 years old and has a score of 2.54
John is 67 years old and has a score of 4.73

方法2:用Pandas的apply()方法(更高效,推荐)

如果你的数据集比较大,apply()是更符合Pandas风格的做法,还能把结果直接存入DataFrame的新列:

import pandas as pd
df = pd.read_csv('data.csv')
message = "{} is {} years old and has a score of {}"

# 定义生成消息的函数
def build_message(row):
    return message.format(row['A'], row['B'], row['C'])

# 对每行应用函数,生成新列
df['formatted_message'] = df.apply(build_message, axis=1)

# 查看结果
print(df[['A', 'B', 'C', 'formatted_message']])

也可以用lambda简化成一行代码:

df['formatted_message'] = df.apply(lambda row: message.format(row['A'], row['B'], row['C']), axis=1)

额外技巧:用命名占位符提升可读性

如果担心占位符顺序搞混,可以把消息改成带命名的格式,然后用关键字参数传入:

message_named = "{name} is {age} years old and has a score of {score}"
df['formatted_message'] = df.apply(lambda row: message_named.format(
    name=row['A'],
    age=row['B'],
    score=row['C']
), axis=1)

另外,如果需要格式化分数的小数位数(比如保留1位),可以修改占位符:

message_formatted = "{} is {} years old and has a score of {:.1f}"

这样分数会自动四舍五入成指定的小数位数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:26:19