代码之家  ›  专栏  ›  技术社区  ›  Night Walker

将数据帧多索引合并到字符串列

  •  2
  • Night Walker  · 技术社区  · 8 年前

    我有以下数据框:

    df = pd.DataFrame([[1,2,3], [11,22,33]], columns = ['A', 'B', 'C'])
    df.set_index(['A', 'B'], inplace=True)
    
            C
    A  B     
    1  2    3
    11 22  33
    

    如何使附加的“文本”列成为多索引的字符串组合。

    不删除索引!

    例如:

            C    D
    A  B            
    1  2    3    1_2
    11 22  33  11_22
    
    4 回复  |  直到 8 年前
        1
  •  3
  •   Bharath M Shetty    8 年前

    也许一个简单的清单理解可能会有帮助,例如

    df['new'] = ['_'.join(map(str,i)) for i in df.index.tolist()]
    
            C    new
    A  B            
    1  2    3    1_2
    11 22  33  11_22
    
        2
  •  2
  •   jezrael    8 年前

    解决方案 python 3.6 :

    df['new'] = [f'{i}_{j}' for i, j in df.index]
    print (df)
            C    new
    A  B            
    1  2    3    1_2
    11 22  33  11_22
    

    如下:

    df['new'] = ['{}_{}'.format(i,j) for i, j in df.index]
    
        3
  •  2
  •   KRKirov    8 年前

    有这么多优雅的方法,选择哪一种还不清楚。因此,这里是对其他答案中提供的方法的性能比较,加上两种情况的可选方法:1)多索引由整数组成;2)多索引由字符串组成。

    在这两种情况下,耶兹拉尔的方法(f_3)都是成功的。然而,对于第二种情况,黑暗是最慢的。由于类型转换步骤的原因,方法1对整数的性能非常差,但对于字符串,它的速度与f_3一样快。

    案例1:

    df = pd.DataFrame({'A': randint(1, 10, num_rows), 'B': randint(10, 20, num_rows), 'C': randint(20, 30, num_rows)})
    df.set_index(['A', 'B'], inplace=True)
    
    # Method 1
    def f_1(df): 
        df['D'] = df.index.get_level_values(0).astype('str') + '_' + df.index.get_level_values(1).astype('str')
        return df
    
    ## Method 2
    def f_2(df):
        df['D'] = ['_'.join(map(str,i)) for i in df.index.tolist()]
        return df
    
    ## Method 3
    def f_3(df): 
        df['D'] = [f'{i}_{j}' for i, j in df.index]
        return df
    
    ## Method 4
    def f_4(df): 
        df['new'] = df.index.map('{0[0]}_{0[1]}'.format)
        return df
    

    enter image description here

    案例2:

    alpha = list("abcdefghijklmnopqrstuvwxyz")
    df = pd.DataFrame({'A': np.random.choice(alpha, size=num_rows), \
                         'B': np.random.choice(alpha, size=num_rows), \
                         'C': randint(20, 30, num_rows)})
    df.set_index(['A', 'B'], inplace=True)
    
    # Method 1
    def f_1(df): 
        df['D'] = df.index.get_level_values(0) + '_' + df.index.get_level_values(1)
        return df
    

    enter image description here

        4
  •  1
  •   Scott Boston    8 年前

    用途:

    df['new'] = df.index.map('{0[0]}_{0[1]}'.format)
    

    输出:

            C    new
    A  B            
    1  2    3    1_2
    11 22  33  11_22