【问题标题】:Passing data from a Pandas Dataframe into a String using the string.format() Method使用 string.format() 方法将数据从 Pandas Dataframe 传递到 String
【发布时间】:2020-02-25 15:44:57
【问题描述】:

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

代码:

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

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

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

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

message.format()

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

非常感谢您的帮助/帮助。

【问题讨论】:

    标签: python string pandas format


    【解决方案1】:

    你可以试试这个:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 2021-12-27
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 2016-05-08
      相关资源
      最近更新 更多