【问题标题】:Python dataframe to list of dictionaries grouped by columnPython数据框到按列分组的字典列表
【发布时间】:2021-06-26 00:05:17
【问题描述】:

我有下表:

Pattern tag Responses
hi greeting Hey :-)
hey greeting Hello, thanks for visiting
how are you greeting Hi there, what can I do for you?
Is anyone there? greeting Hi there, how can I help?
Bye goodbye See you later, thanks for visiting
See you later goodbye Have a nice day
Goodbye goodbye Bye! Come back again soon

我想通过“标签”对其进行分组并获得以下json格式:

{
  "intents": [
    {
      "tag": "greeting",
      "patterns": [
        "Hi",
        "Hey",
        "How are you",
        "Is anyone there?"
      ],
      "responses": [
        "Hey :-)",
        "Hello, thanks for visiting",
        "Hi there, what can I do for you?",
        "Hi there, how can I help?"
      ]
    },
    {
      "tag": "goodbye",
      "patterns": ["Bye", "See you later", "Goodbye"],
      "responses": [
        "See you later, thanks for visiting",
        "Have a nice day",
        "Bye! Come back again soon"
      ]
    }
  ]
}

我尝试了很多东西,例如以下:

df.groupby('tag').apply(lambda x: list(x['Pattern']))

但这并不是我想要的……有人有什么建议吗?

【问题讨论】:

    标签: python json dataframe dictionary


    【解决方案1】:

    您可以使用此示例如何将数据框格式化为您的 Json 格式:

    import json
    
    tmp = (
        df.groupby("tag")
        .apply(
            lambda x: dict(
                patterns=x["Pattern"].to_list(), responses=x["Responses"].to_list()
            )
        )
        .to_dict()
    )
    
    out = {"intents": []}
    for k, v in tmp.items():
        out["intents"].append({})
        out["intents"][-1]["tag"] = k
        out["intents"][-1]["patterns"] = v["patterns"]
        out["intents"][-1]["responses"] = v["responses"]
    
    print(json.dumps(out, indent=4))
    

    打印:

    {
        "intents": [
            {
                "tag": "goodbye",
                "patterns": [
                    "Bye",
                    "See you later",
                    "Goodbye"
                ],
                "responses": [
                    "See you later, thanks for visiting",
                    "Have a nice day",
                    "Bye! Come back again soon"
                ]
            },
            {
                "tag": "greeting",
                "patterns": [
                    "hi",
                    "hey",
                    "how are you",
                    "Is anyone there?"
                ],
                "responses": [
                    "Hey :-)",
                    "Hello, thanks for visiting",
                    "Hi there, what can I do for you?",
                    "Hi there, how can I help?"
                ]
            }
        ]
    }
    

    【讨论】:

      【解决方案2】:

      这里有一个解决方案:

      def create_dic(x):
          
          d = {'tag': list(set(x['tag']))[0], 'patterns' : list(set(x['Pattern'])) , 'responses': list(set(x['Responses']))} 
          return d
      
      result = {"intents"  : list( dict(df.groupby('tag').apply(lambda x: create_dic(x))).values()) }
      
      

      输出:

      print(result)
      {'intents': [{'tag': 'goodbye',
         'patterns': ['Goodbye', 'Bye', 'See you later'],
         'responses': ['Bye! Come back again soon',
          'Have a nice day',
          'See you later, thanks for visiting']},
        {'tag': 'greeting',
         'patterns': ['Is anyone there?', 'how are you', 'hi', 'hey'],
         'responses': ['Hi there, how can I help?',
          'Hey :-)',
          'Hi there, what can I do for you?',
          'Hello, thanks for visiting']}]}
      

      【讨论】:

        猜你喜欢
        • 2017-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-18
        • 2021-04-10
        • 2016-10-10
        • 2020-05-15
        • 1970-01-01
        相关资源
        最近更新 更多