基于列名的值重命名列名

2024-06-23 19:54:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的数据框

df 

col_1    col_2     col_3
min1     max1     target1
min2     max2     target2

我想根据列的值分别将列col_1、col_2、col_3重命名为Min、Max和Target。因此,我希望有以下内容

Min     Max     Target
min1    max1    target1
min2    max2    target2

有人能给我演示一个使用python实现这一点的简单技巧吗


Tags: 数据targetdf技巧colminmax重命名
1条回答
网友
1楼 · 发布于 2024-06-23 19:54:16

嗯,我不确定你是否应该这样重命名列,但是这里有一种方法你可以这样做。首先使用remove numbers from string,然后使用most common string

from collections import Counter

cols = [Counter(df[col].str.replace('\d+', '')).most_common()[0][0].capitalize()
        for col in df.columns
        ]

df.columns = cols

输出:

    Min     Max     Target
0   min1    max1    target1
1   min2    max2    target2

相关问题 更多 >

    热门问题