【问题标题】:Rename a df column by that have same names by iterating column indexes-pandas通过迭代列索引-pandas 重命名具有相同名称的 df 列
【发布时间】:2019-07-10 01:32:22
【问题描述】:

我有一个像这样的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 可以重命名整个数据框的列,但这不是我想要的,因为我正在自动化一些任务。如何使用列索引获得所需的输出?

另外,我可以在列表理解方法中重命名熊猫列吗?

任何想法都会很棒。

【问题讨论】:

    标签: python-3.x pandas multiple-columns rename


    【解决方案1】:

    可以使用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】:

    这个也可以

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 2022-07-25
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2022-07-11
      相关资源
      最近更新 更多