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

通过迭代列索引pandas重命名具有相同名称的df列

  •  0
  • user9431057  · 技术社区  · 7 年前

    我有一个 pandas 像这样的数据帧,

       Name     Not_Included  Quantity Not_Included  
    0  Auto     DNS           10       DNS
    1  NaN      DNS           12       DNS
    2  Rtal     DNS           18       DNS
    3  NaN      DNS           14       DNS
    4  Indl     DNS           16       DNS
    5  NaN      DNS           18       DNS
    

    现在,我想重新命名 Not_Included 使用数据帧的列索引。所以,我得到这样的输出,

           Name     Not_Included_1  Quantity Not_Included_3  
        0  Auto     DNS             10       DNS
        1  NaN      DNS             12       DNS
        2  Rtal     DNS             18       DNS
        3  NaN      DNS             14       DNS
        4  Indl     DNS             16       DNS
        5  NaN      DNS             18       DNS
    

    我试了以下几点,

    for c,v in enumerate(s_df):
        if v == 'Not_Included':
            vi = 'Not_Included' + str(c)
            s_df.rename(columns=lambda n: n.replace(v, vi), inplace=True)
    

    我得到以下结果,

        Name    Not_Included31  Quantity  Not_Included31
    0   Auto    DNS             10        DNS
    1   NaN     DNS             12        DNS
    2   Rtal    DNS             18        DNS
    3   NaN     DNS             14        DNS
    4   Indl    DNS             16        DNS
    5   NaN     DNS             18        DNS
    

    posts 重命名整个数据帧的列,但这不是我要找的,因为我正在自动执行一些任务。如何使用列索引获得所需的输出?

    另外,我可以在重命名pandas列的列表理解方法中完成吗?

    任何想法都很好。

    0 回复  |  直到 7 年前
        1
  •  2
  •   ALollz    7 年前

    可以使用 np.where 要设置列,请检查其重复的位置。

    import numpy as np
    
    df.columns = np.where(df.columns.duplicated(),  
                          [f'{df.columns[i]}_{i}' for i in range(len(df.columns))],
                          df.columns)
    

    索引也有where方法:

    df.columns = df.columns.where(~df.columns.duplicated(),
                                  [f'{df.columns[i]}_{i}' for i in range(len(df.columns))])
    

    输出:

       Name Not_Included  Quantity Not_Included_3
    0  Auto          DNS        10            DNS
    1   NaN          DNS        12            DNS
    2  Rtal          DNS        18            DNS
    
        2
  •  0
  •   Terry    7 年前

    这也行

    df.columns = ['{}_{}'.format(coluna, index) if 'Not_Included' in coluna else coluna for index, coluna in enumerate(df.columns)]