【问题标题】:Pandas Delete Duplicate Col Names with Specific Col NamePandas 删除具有特定列名的重复列名
【发布时间】:2021-09-20 19:21:07
【问题描述】:

我在网上找不到答案。假设我有一个看起来像这样的 df1,并带有以下列名称,并且我不能像大多数在线答案所建议的那样,只对所有重复的 col 名称使用 drop。

index   year   season   1      2      3     year   season   1      2      3
0       1991   winter   7.1    8.3    9.0   1991   spring   0.5    7.2    1.5
1       1992   winter   4.2    5.1    8.2   1991   spring   2.9    6.2    8.1

但是,我需要列名看起来像这样,方法是删除/删除“year”的后续列名,但保留“1,2,3”和“season”的重复列名,以便最终的新 df2 看起来像这样:

index   year   season   1      2      3     season   1      2      3
0       1991   winter   7.1    8.3    9.0   spring   0.5    7.2    1.5
1       1992   winter   4.2    5.1    8.2   spring   2.9    6.2    8.1

谢谢,

【问题讨论】:

  • 我将评论处理pandas 中的重复标签是有问题的,因为它使函数是否可以返回系列或数据帧变得复杂。 pandas 积极地使列标签难以被复制(通常试图破坏它们以添加 .N),他们这样做是有原因的。
  • 是的,如果我需要按列“1,2,3”进行平均,将“季节”更改为“周期”列名称并将“周期”列的值更改为'cold_wx'?这会给我一个“无法从重复的轴错误重新索引”吗?
  • 您通常可以获得具有 MultiIndex 的类似组织,这将允许复制一个级别,而完整标签,即 ('winter', 1)('spring', 1) 的元组将不被复制。在这种情况下,您可以轻松地在赛季或123 上进行分组,使用 groupby。

标签: pandas duplicates multiple-columns


【解决方案1】:

在你的情况下做

df.loc[:,(df.groupby(level=0,axis=1).cumcount().eq(0)) | (df.columns!='year')]
Out[188]: 
   index  year  season    1    2    3  season    1    2    3
0      0  1991  winter  7.1  8.3  9.0  spring  0.5  7.2  1.5
1      1  1992  winter  4.2  5.1  8.2  spring  2.9  6.2  8.1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2018-05-13
    • 2019-01-05
    • 2020-07-08
    • 2020-12-11
    • 2013-01-03
    相关资源
    最近更新 更多