简体   繁体   English

Pandas 用序号重命名选定的列

[英]Pandas rename selected columns with sequential numbers

I have a df with a number or columns, I would like to rename these with incremental numbers selecting the starting and ending range.我有一个带有数字或列的 df,我想用增量数字重命名这些数字,选择起始和结束范围。

在此处输入图像描述

With the above image, I would like to select only columns BD, and rename them to 1-4.使用上图,我想 select 仅列 BD,并将它们重命名为 1-4。 So the resulting data frame would be:所以生成的数据框将是:

在此处输入图像描述

So basically selecting the headers via index numbers and adding incremental numbers instead.所以基本上通过索引号选择标题并添加增量数字。

EDIT: The above dataframe编辑:上述 dataframe

data = [['a','b','c','d','e','f'], ['a','b','c','d','e','f'], ['a','b','c','d','e','f'],['a','b','c','d','e','f']]

df = pd.DataFrame(data, columns = ['A','B','C','D','E','F'])

Use rename with selected columns by DataFrame.loc - here between B and E :通过DataFrame.loc对选定的列使用rename - 在BE之间:

c = df.loc[:, 'B':'E'].columns
df = df.rename(columns=dict(zip(c, range(1, len(c) + 1))))
print (df)
   A  1  2  3  4  F
0  a  b  c  d  e  f
1  a  b  c  d  e  f
2  a  b  c  d  e  f
3  a  b  c  d  e  f

If this is something you have to do frequently, you can write a custom function for that:如果这是您必须经常做的事情,您可以为此编写自定义 function:

def col_rename(df, start, stop, inplace=False):
    cols = list(df.loc[:, start:stop].columns)
    new_cols = df.columns.map(lambda x: {k:v for v,k in
                                         enumerate(cols, start=1)
                                        }.get(x, x))
    if inplace:
        df.columns = new_cols
    else:
        return new_cols

df.columns = col_rename(df, 'B', 'F')

# or
# col_rename(df, 'B', 'F', inplace=True)

output: output:

   A  1  2  3  4  F
0  0  1  2  3  4  5

used input:使用的输入:

df = pd.DataFrame([range(6)], columns=list('ABCDEF'))

#    A  B  C  D  E  F
# 0  0  1  2  3  4  5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM