【问题标题】:How to create list of f-string (alike) based on pd.DataFrame values? [duplicate]如何根据 pd.DataFrame 值创建 f 字符串(类似)列表? [复制]
【发布时间】:2019-09-19 21:45:27
【问题描述】:

问题
如何根据 pandas DataFrame 的值创建带有占位符(即“f-string”-like)的字符串列表?

示例

假设我有以下数据框:

import pandas as pd

data = [
    ['Alice', 13, 'apples'],
    ['Bob', 17, 'bananas']
]

df = pd.DataFrame(
    data,
    columns=['name', 'qty', 'fruit']
)

如何使用f"{name} ate {qty} {fruit}" 之类的东西作为模式创建字符串列表?
换句话说,如何创建以下列表:

[
    'Alice ate 13 apples',
    'Bob ate 17 bananas'
]

【问题讨论】:

  • 你的意思是(df.name+' ate '+df.qty.astype(str)+' '+df.fruit).tolist() ?
  • @anky_91 是的,你是对的。我还认为您的答案比提供的其他答案更好,因为它避免了 for 循环,并且更(恕我直言)pythonic。您介意将您的评论转换为答案吗?
  • 好的,我加了。
  • @ebosi 抱歉,为什么在接受答案时没有 f 字符串?因为您的问题清楚地表明需要 f 个字符串来解决,所以不需要任何具有预期输出的解决方案。
  • @jezrael 你是对的:我的问题最初的措辞(即在你写下你的答案和后来你的评论时),接受的答案没有回答 问题 本身,而是我面临的问题。我相信 anky_91 的答案更“pythonic”,因为它是一个没有 for 循环的单行……因此,更适合作为“公认的答案”。不过,我很欣赏你的回答。但我知道你可能会感到沮丧,因为我意识到只有在你花时间帮助我之后我才面临 XY 问题。

标签: python pandas dataframe f-string


【解决方案1】:

将列表推导与DataFrame.to_dict 的字典列表一起使用:

a = [f"{x['name']} ate {x['qty']} {x['fruit']}" for x in df.to_dict('r')]
print (a)
['Alice ate 13 apples', 'Bob ate 17 bananas']

或者:

a = [f"{name} ate {qty} {fruit}" for name, qty, fruit in df[['name','qty','fruit']].values]

【讨论】:

    【解决方案2】:

    将此作为答案,我们可以合并列并在最后调用.tolist()

    (df.name+' ate '+df.qty.astype(str)+' '+df.fruit).tolist()
    

    输出:

    ['Alice ate 13 apples', 'Bob ate 17 bananas']
    

    【讨论】:

      【解决方案3】:

      使用

      pandas.apply:

      df.apply(lambda x: x['name'] + " ate " + str(x['qty']) + " " + x['fruit'],1).values
      

      【讨论】:

        猜你喜欢
        • 2012-12-23
        • 2012-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-26
        • 2012-01-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多