代码之家  ›  专栏  ›  技术社区  ›  Frâncio Rodrigues

基于列值重新索引任务

  •  4
  • Frâncio Rodrigues  · 技术社区  · 7 年前

    我有一个数据帧,其中有数百万行具有唯一索引,还有一列('b')具有多个重复值。

    "old_index1,old_index2" )其中“b”具有重复的值,但对于“b”具有唯一值的行保持不变。“b”列的值应该保持不变,就像在a中一样 keep=first 战略。下面的例子。

    输入数据帧:

    df = pd.DataFrame(data = [[1,"non_duplicated_1"],
                              [2,"duplicated"],
                              [2,"duplicated"],
                              [3,"non_duplicated_2"],
                              [4,"non_duplicated_3"]],
                      index=['one','two','three','four','five'],
                      columns=['a','b'])
    

    期望输出:

                 a                 b
    one          1  non_duplicated_1
    two,three    2        duplicated
    four         3  non_duplicated_2
    five         4  non_duplicated_3
    

    实际的数据帧相当大,所以我想避免非矢量化操作。

    我发现这非常困难…有什么想法吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   sacuL    7 年前

    你可以用 transform 在索引列上(使用 reset_index b

    df.index = df.reset_index().groupby('b')['index'].transform(','.join)
    
    df.drop_duplicates('b',inplace=True)
    
    >>> df
               a                 b
    index                         
    one        1  non_duplicated_1
    two,three  2        duplicated
    four       3  non_duplicated_2
    five       4  non_duplicated_3
    
        2
  •  2
  •   user3483203    7 年前

    安装程序

    dct = {'index': ','.join, 'a': 'first'}
    

    你可以 reset_index 使用前 groupby ,尽管我不清楚你为什么要这样:

    df.reset_index().groupby('b', as_index=False, sort=False).agg(dct).set_index('index')
    

                              b  a
    index
    one        non_duplicated_1  1
    two,three        duplicated  2
    four       non_duplicated_2  3
    five       non_duplicated_3  4