【问题标题】:Selecting more than 1 F'string in dataframe. python?在数据框中选择超过 1 个 F\'string。 Python?
【发布时间】:2022-10-12 21:27:39
【问题描述】:

我有一个使用谷歌日历 API 的示例代码,它要求数据是一个字符串值。我使用 df.iat,而不是每次更改数据框时手动键入字符串。这就是我到目前为止所拥有的,并且适用于单个值。

Create an event
"""
event = {
  'summary':f'{df.iat[0,0]}',
  'description': f'{df.iat[0,1]}',
  'start': {
    'date': '2022-04-04',
  },
  'end': {
    'date': '2022-04-04',

打印出来

summary = Order
description = Plastic Cups
date 04-04-2022

但我需要将多个值拉入一个字符串。我如何执行此操作才能正常工作 例如在描述中

I want to do f'{df.iat[1,1]}',f'{df.iat[0,1]}'
which would print out description = 7000  Plastic Cups

但是我使用它时遇到了错误,我尝试了 dfiloc,我也尝试了一个示例

(("test"),(f'{df.iat[0,1]}')

这只会打印出“测试”部分,而不是 df.iat 字符串

我已经被困在这几个小时了,任何帮助将不胜感激。

【问题讨论】:

  • 您可以在格式化字符串中包含任意数量的变量。例如:f"some info: {df.iat[1,1]}, some other info {df.iat[0,1]}"
  • 哇,我不敢相信我错过了那种格式。非常感谢你,请发表一个答案,这样我就可以投票了。

标签: python pandas dataframe


【解决方案1】:

Python中的f-strings,也称为Literal String Interpolation,可以同时处理多个变量。例如:

orderID = 012345
orderName = "foo"

message = f"Your order {orderName} with orderID {orderID} was registered!"

如果您打印上述message 变量:
Your order foo with orderID 012345 was registered!

有关此的更多信息:PEP-0498

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2013-10-22
    • 2015-08-15
    • 2011-07-03
    • 1970-01-01
    • 2017-03-10
    • 2013-12-17
    • 2016-09-02
    • 2021-02-21
    相关资源
    最近更新 更多