使用string.format()方法将数据从Pandas数据帧传递到String中 [英] Passing data from a Pandas Dataframe into a String using the string.format() Method

查看:211
本文介绍了使用string.format()方法将数据从Pandas数据帧传递到String中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中包含姓名,年龄和分数.我想做的是使用format()方法将名称,年龄和分数传递到消息(字符串)中.

I have a dataframe which includes names, age and score. What I'm trying to do is pass the name, age and score into a message (a string) using the format() method.

代码:

import pandas as pd

df = pd.read_csv('data.csv')

df

      A     B      C
0    Matt  23    0.98
1    Mark  34    9.33
2    Luke  52    2.54
3    John  67    4.73

我想将此数据传递到的消息:

The message I want to pass this data into:

message = "{} is {} years old and has a score of {}"

我对将.format()方法与消息(字符串)一起使用的理解有限

My limited understanding of using the .format() method with the message (string)

message.format()

据我所知,我需要将数据框作为format()方法的参数之一,但是除此之外,我不确定如何编写该代码.

From what I can tell, I need to have the dataframe as 1 of the arguments for the format() method, butother than that, I'm unsure as to how to code this up.

非常感谢您的帮助/协助.

Help/assistance is greatly appreciated.

推荐答案

您可以尝试以下操作:

import pandas as pd

df = pd.DataFrame([['Matt',23,0.98],['Mark',34,0.43]])
message = "{} is {} years old and has a score of {}"
for i,r in df.iterrows():
    print(message.format(*r.to_dict().values()))

输出:

Matt is 23 years old and has a score of 0.98
Mark is 34 years old and has a score of 0.43

这篇关于使用string.format()方法将数据从Pandas数据帧传递到String中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆