【问题标题】:Format an f-string for each dataframe object为每个数据框对象格式化一个 f 字符串
【发布时间】:2021-12-16 14:59:52
【问题描述】:

要求

我的要求是让 Python 代码从数据库中提取一些记录,格式化并发布到 Slack 频道。

计划的方法

由于 Slack 消息块是 JSON,我打算

1. 为每个块创建类似 JSON 的模板。例如

 json_template_str = '{{
   "type": "section",
   "fields": [
       {{
           "type": "mrkdwn",
           "text": "Today *{total_val}* customers saved {percent_derived}%."
       }}
     ]
 }}'

2. 从数据库中提取记录到数据帧。

3. 循环遍历数据帧并使用 .format(**locals())) 之类的东西批量替换 {var} 变量

4. 使用 Slack API 发布格式化的 JSON

问题

我以前没有使用过数据框。 完成 第 3 步 的最佳方法是什么?目前我是

3.1 逐个循环遍历数据框对象for i, df_row in df.iterrows():

3.2分配

    total_val= df_row['total_val']
    percent_derived= df_row['percent_derived']

3.3 在循环格式中添加str到列表block.append(json.loads(json_template_str.format(**locals()))

我试图在 dataframe 中使用 assign() 方法,但无法找到一种像 lambda 函数一样使用的方法来创建一个具有我可以使用的预期值的新列。

作为 pandas 的新手,我觉得可能有更有效的方法来做到这一点(甚至可能涉及更改 JSON 模板字符串 - 我完全可以做到)。很高兴听到想法和想法。

感谢您的宝贵时间。

【问题讨论】:

    标签: python pandas string dataframe slack-block-kit


    【解决方案1】:

    我不会手动写一个 JSON 字符串,而是创建一个对应的 python 对象,然后使用json 库将其转换为字符串。考虑到这一点,您可以尝试以下方法:

    import copy
    import pandas as pd
    
    # some sample data
    df = pd.DataFrame({
        'total_val': [100, 200, 300],
        'percent_derived': [12.4, 5.2, 6.5]
    })
    
    # template dictionary for a single block
    json_template = {
        "type": "section",
        "fields": [
            {"type": "mrkdwn",
             "text": "Today *{total_val:.0f}* customers saved {percent_derived:.1f}%."
            }
        ]
    }
    
    # a function that will insert data from each row 
    # of the dataframe into a block
    def format_data(row):
        json_t = copy.deepcopy(json_template)
        text_t = json_t["fields"][0]["text"]
        json_t["fields"][0]["text"] = text_t.format(
            total_val=row['total_val'], percent_derived=row['percent_derived'])
        return json_t
    
    # create a list of blocks
    result = df.agg(format_data, axis=1).tolist()
    

    结果列表如下所示,如果需要,可以转换为 JSON 字符串:

    [{
        'type': 'section',
        'fields': [{
            'type': 'mrkdwn',
            'text': 'Today *100* customers saved 12.4%.'
        }]
    }, {
        'type': 'section',
        'fields': [{
            'type': 'mrkdwn',
            'text': 'Today *200* customers saved 5.2%.'
        }]
    }, {
        'type': 'section',
        'fields': [{
            'type': 'mrkdwn',
            'text': 'Today *300* customers saved 6.5%.'
        }]
    }]
    

    【讨论】:

    • 非常感谢您抽出宝贵时间详细回复。目标是将格式保存在 json 文件中,以便无需更改 py 代码即可更改文件。这也是查看.format(**locals())) 的原因,因为我们在数据字典中有属性列表,并且差异团队可以将差异格式与他们正在使用的属性一起使用。我在问题中省略了这个细节,所以我实际上不会使用像 json_template_str = '{{ 这样的字符串,而是读取一个包含模板代码的 json 文件。
    • 话虽如此,再次感谢您抽出时间并分享您的方法。因为我是这里的新手,所以我不能为你的答案投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多