重命名数据切片的列上的列未按预期执行 [英] Renaming columns on slice of dataframe not performing as expected

查看:44
本文介绍了重命名数据切片的列上的列未按预期执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图清除数据框中的列名,但只清除部分列.

I was trying to clean up column names in a dataframe but only a part of the columns.

当尝试以某种方式替换数据框切片上的列名称时,它不起作用,为什么?

It doesn't work when trying to replace column names on a slice of the dataframe somehow, why is that?

让我们说我们有以下数据框:
注意,底部是可复制的代码以重现数据:

Lets say we have the following dataframe:
Note, on the bottom is copy-able code to reproduce the data:

   Value ColAfjkj ColBhuqwa ColCouiqw
0      1        a         e         i
1      2        b         f         j
2      3        c         g         k
3      4        d         h         l

我要清理列名(预期输出):

I want to clean up the column names (expected output):

   Value ColA ColB ColC
0      1    a    e    i
1      2    b    f    j
2      3    c    g    k
3      4    d    h    l


方法1 :

我可以这样获得干净的列名:

I can get the clean column names like this:

df.iloc[:, 1:].columns.str[:4]

Index(['ColA', 'ColB', 'ColC'], dtype='object')

方法2 :

s = df.iloc[:, 1:].columns
[col[:4] for col in s]

['ColA', 'ColB', 'ColC']


但是,当我尝试覆盖列名时,什么也没发生:


But when I try to overwrite the column names, nothing happens:

df.iloc[:, 1:].columns = df.iloc[:, 1:].columns.str[:4]

   Value ColAfjkj ColBhuqwa ColCouiqw
0      1        a         e         i
1      2        b         f         j
2      3        c         g         k
3      4        d         h         l

与第二种方法相同:

s = df.iloc[:, 1:].columns
cols = [col[:4] for col in s]

df.iloc[:, 1:].columns = cols

   Value ColAfjkj ColBhuqwa ColCouiqw
0      1        a         e         i
1      2        b         f         j
2      3        c         g         k
3      4        d         h         l


这确实有效,但是您必须手动连接第一列的名称,这并不理想:


This does work, but you have to manually concat the name of the first column, which is not ideal:

df.columns = ['Value'] + df.iloc[:, 1:].columns.str[:4].tolist()

   Value ColA ColB ColC
0      1    a    e    i
1      2    b    f    j
2      3    c    g    k
3      4    d    h    l

有没有更简单的方法来实现这一目标?我想念什么吗?

Is there an easier way to achieve this? Am I missing something?

要复制的数据帧:

df = pd.DataFrame({'Value':[1,2,3,4],
                   'ColAfjkj':['a', 'b', 'c', 'd'],
                   'ColBhuqwa':['e', 'f', 'g', 'h'],
                   'ColCouiqw':['i', 'j', 'k', 'l']})

推荐答案

这是因为熊猫的索引是不可变的.如果您查看 class pandas的文档.索引 ,您会看到它定义为:

This is because pandas' index is immutable. If you check the documentation for class pandas.Index, you'll see that it is defined as:

不可变的ndarray实现有序的,可切片的集合

Immutable ndarray implementing an ordered, sliceable set

因此,要对其进行修改,您必须创建一个新的列名列表,例如:

So in order to modify it you'll have to create a new list of column names, for instance with:

df.columns = [df.columns[0]] + list(df.iloc[:, 1:].columns.str[:4])


另一种选择是使用 使用包含要替换列的字典的重命名 :

df.rename(columns=dict(zip(df.columns[1:], df.columns[1:].str[:4])))

这篇关于重命名数据切片的列上的列未按预期执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆