【问题标题】:Parsing a JSON in dataframe column in order of occurence按出现顺序解析数据框列中的 JSON
【发布时间】:2020-03-10 00:04:37
【问题描述】:

我有一个数据框,其中有一列包含 JSON 之类的 -

Player ID               Response
    1                 [{'id': '1-4', 'content': 'Develop'}, {'id': '1-3', 'content': 'Networking'}, {'id': '1-5', 'content': 'Opportunity'}]
    2                 [{'id': '1-4', 'content': 'Develop'}]
    3                 [{'id': '1-3', 'content': 'Networking'}, {'id': '1-4', 'content': 'Develop'}, {'id': '1-2', 'content': 'Excuse'}]
    4                 [{'id': '1-4', 'content': 'Develop'}, {'id': '1-6', 'content': 'Gain'}, {'id': '1-1', 'content': 'Different'}]  

Response 列按顺序包含 1-3 个实体。我需要将此列重新排序为 -

  ID              Score     InResponse 
  1-1                1          1
  1-2                1          1
  1-3                5          2
  1-4               11          4 
  1-5                1          1
  1-6                2          1   

其中,如果一个 ID 排名第一,则获得 3 分,如果排名第二,则获得 2 分,如果排名第三,则获得 1 分。因此,例如,1-4 在 3 个响应中排名第 1,在 1 个响应中排名第 2,因此,3x3 + 1x2 = 11 ptsInResponse 表示该 ID 在数据框中出现的次数。

我试过了

pd.io.json.json_normalize(df.Q1.to_dict())

但由于某种原因,它给了我意想不到的结果。我该怎么做?

【问题讨论】:

    标签: json python-3.x pandas dataframe


    【解决方案1】:

    这样做的一种方法是在您的数据框中应用一个函数,该函数将您需要添加到每个 JSON 元素的任何元数据附加到每个 JSON 元素中,然后将行单独分组回一个数据框,然后应用分组,例如在 python3 中。

    # import data
    df = pd.DataFrame(columns=['Player ID', 'Response'], 
                      data=[
                         [1,[{'id': '1-4', 'content': 'Develop'}, {'id': '1-3', 'content': 'Networking'}, {'id': '1-5', 'content': 'Opportunity'}]],
                         [2, [{'id': '1-4', 'content': 'Develop'}]],
                         [3, [{'id': '1-3', 'content': 'Networking'}, {'id': '1-4', 'content': 'Develop'}, {'id': '1-2', 'content': 'Excuse'}]],
                         [4, [{'id': '1-4', 'content': 'Develop'}, {'id': '1-6', 'content': 'Gain'}, {'id': '1-1', 'content': 'Different'}]]])
    
    
    arr = []
    def insert_metadata(row):
        i=0
        for item in row:
            item['score'] = 3-i 
            item['In Response'] = 1
            i+=1
            arr.append(item)
        return row
    
    df['Response'].apply(insert_metadata)
    final_df = pd.DataFrame(arr)
    final_df.groupby('id').sum().reset_index()
    

    【讨论】:

      【解决方案2】:

      我是这样做的 -

      dict_response = {'1-1':0, '1-2':0, '1-3':0, '1-4':0, '1-5':0, '1-6':0, '1-7':0}
      dict_occurrence = {'1-1':0, '1-2':0, '1-3':0, '1-4':0, '1-5':0, '1-6':0, '1-7':0}
      for index, row in df.iterrows():
          dict_temp = json.loads(row['Response'].replace("'", '"'))
          dict_response[list(dict_temp[0].values())[0]] += 3
          dict_occurrence[list(dict_temp[0].values())[0]] += 1
          if len(dict_temp) > 1:
              dict_response[list(dict_temp[1].values())[0]] += 2
              dict_occurrence[list(dict_temp[1].values())[0]] += 1
          if len(dict_temp) > 2:
              dict_response[list(dict_temp[2].values())[0]] += 1
              dict_response[list(dict_temp[2].values())[0]] += 1
      
      df_q1_responses = pd.DataFrame()
      df_q1_responses['ID'] = dict_response.keys()
      df_q1_responses['Points'] = df_q1_responses['ID'].map(dict_response)
      df_q1_responses['Responses'] = df_q1_responses['ID'].map(dict_occurrence)
      df_q1_responses
      

      但我不太喜欢我的解决方案。如果您有任何改进或替代解决方案,请告诉我!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-15
        • 1970-01-01
        • 2021-10-10
        • 2013-06-03
        • 2013-10-30
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        相关资源
        最近更新 更多