Passing data from a Pandas Dataframe into a String using the string.format() Method

为君一笑 提交于 2020-01-25 08:59:48

问题


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.

Code:

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 {}"

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

message.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.


回答1:


You can try this:

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()))

Output:

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


来源:https://stackoverflow.com/questions/58623743/passing-data-from-a-pandas-dataframe-into-a-string-using-the-string-format-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!