【问题标题】:How can I print float in Pandas?如何在 Pandas 中打印浮点数?
【发布时间】:2019-12-12 18:24:23
【问题描述】:

我想打印这样的东西:

print("Average age is: " +  round(data.loc[data["School1"]==1]["Age"].mean(),2)

不过我有一个 TypeError:can only concatenate str (not "float") to str

我的浮点数,表示round(data.loc[data["School1"]==1]["Age"].mean(),2) = 15.23

如何打印?

【问题讨论】:

  • + 更改为 ,。可能也值得研究f-strings

标签: python string pandas printing


【解决方案1】:

错误告诉您它不知道如何连接(连接)floatstring。换句话说,它不知道添加 (+) 和 stringfloat 的含义。

val=round(data.loc[data["School1"]==1]["Age"].mean(),2)
print("float value: {}".format(val))

val=data.loc[data["School1"]==1]["Age"].mean()
print("float value: %.2f" % val) 

两者都应该有效。如果您仍然卡住,我可以进行测试并提供更多信息,但示例 data 对象会很有用。

注意事项:

  • 不需要中间的val,但我想保持print 语句干净。
  • %.2f 将浮点数限制为 2 位小数,因此在第二种方法中不需要调用 round()
  • 以上两种方法都可以支持多次插入:
    • 例如:print("{} {}".format("hello","world")) 将打印hello world
    • 第二种方法类似于print("%s %s" % ("hello", "world"))
  • 对于第二种方法,除了%s(字符串)和%f(浮点数)之外,还有其他选择。

https://pyformat.info/ 会更详细地讨论这两种方法,您可能会发现它很有帮助。

您需要做的最少更改是使用str() 方法包装您的float,将其从float 转换为string(参见本段下方的代码块)。完成后,python 知道如何使用 + 运算符连接两个字符串。它会起作用,但我认为它会使事情变得混乱,尤其是当您将多个变量转换并连接成一个字符串变量或打印语句时。

print("Average age is: " +  str(round(data.loc[data["School1"]==1]["Age"].mean(),2)))

【讨论】:

    【解决方案2】:

    使用您的代码,您可以通过在函数的值之前添加str() 使其工作,因为正如错误指出的那样,您无法连接(使用+ 运算符)带有浮点数的字符串。

    print("Average age is: " +  str(round(data.loc[data["School1"]==1]["Age"].mean(),2))
    

    【讨论】:

      【解决方案3】:

      可以通过使用 {} 括号来打印浮点数,以指定值在字符串中的位置,然后使用 .format 将这些括号(按顺序)替换为您想要的值打印:

      print("float value: {}".format(round(data.loc[data["School1"]==1]["Age"].mean(),2)))
      

      【讨论】:

        【解决方案4】:

        如果你使用的是python3.6,可以使用f字符串如下

        print(f'Average age is: {round(data.loc[data["School1"]==1]["Age"].mean(),2)}')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-29
          • 2021-08-19
          • 1970-01-01
          • 1970-01-01
          • 2021-12-17
          • 2020-08-04
          相关资源
          最近更新 更多