代码之家  ›  专栏  ›  技术社区  ›  user3871

在匹配值处插入多行

  •  0
  • user3871  · 技术社区  · 6 年前

    使用Pandas,我想为给定的匹配id插入多行 matchid .

    意思是,我现在将结果列表串起来,并插入到现有的DF中的给定行中:

    matchid  |  events_categories 
    -----------------------------
    0           event_a, event_b, event_c
    1           event_b
    

    我想要的是,对于给定的匹配 匹配ID 行,在以下行之间插入多行:

    matchid  |  events_categories 
    -----------------------------
    0           event_a
    0           event_b
    0           event_c
    1           event_b
    

    我用的是 匹配ID 因为返回的结果来自异步请求。这些值不能保证顺序正确。所以我将响应对象映射回dataframe行。

    蟒蛇:

    rs = (grequests.get(u, headers=headers, hooks={'response': 
    add_filename_to_response}) for u in urls)
    results = grequests.map(rs, exception_handler=exception_handler)
    
    for event_obj in results:
        jsonObj = event_obj.json()
        categories = []
        try:
            for res in jsonObj['results']:
                categories.append(res['category'])
                ### How can I insert at the given row here?
                ### "df.loc[df['matchid']==event_obj.matchid, 'event_categories'] = res['category']" overwrites each value
    
        except: None
    
        ### Pair the row to the event_obj via mapping_key
    
        df.loc[df['matchid']==event_obj.matchid, 'event_categories'] = ', '.join(str(x) for x in categories)
    
    ...
    
    
    '''
    In the AJAX response callback, add additional meta data to the response object
    '''
    def add_filename_to_response(response, *args, **kwargs):
        ### Get filepath from the ?filepath= param in the URL string
        obj_matchid = response.url.split('matchid=')[1].split('&')[0]
        ### Append mapping key to AJAX response object
        response.matchid = obj_matchid
    
        return response
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   BENY    6 年前

    这是不必要的

    s=df['events_categories'].str.split(',')
    pd.DataFrame({'matchid':df['matchid'].repeat(s.str.len()),'events_categories':np.concatenate(s.values)})
    Out[517]: 
      events_categories  matchid
    0           event_a        0
    0           event_b        0
    0           event_c        0
    1           event_b        1