如何用 python 中的数字重命名多个列?

How can I rename multiple columns with numbers in python?

我有一个包含 ~2400 列的数据框,我想将所有列从 1 重命名为 2400
我当前的列名称是数字,几乎所有列都是重复的。

我正在尝试类似的方法,但它不起作用:

# An example
import pandas as pd
# Create an example dataframe
data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'],'Score': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])

ncol = len(df.columns)
for col in df.columns :
    for i in range(ncol) :
        df.rename(columns={col: str(i)}, inplace=True)

提前致谢。

IIUC 你可以做到

df.columns = pd.Index(np.arange(1,len(df.columns)+1).astype(str)

所以这只是用从 np.arange 生成的新 Index 对象覆盖列,我们使用 astype

将 dtype 转换为 str

示例:

In [244]:
df = pd.DataFrame(np.random.randn(4,4))
df.columns

Out[244]:
RangeIndex(start=0, stop=4, step=1)

In [243]:
df.columns = pd.Index(np.arange(1,len(df.columns)+1)).astype(str)
df.columns

Out[243]:
Index(['1', '2', '3', '4'], dtype='object')

以你的例子为例:

In [245]:
data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'],'Score': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df.columns = pd.Index(np.arange(1,len(df.columns)+1)).astype(str)
df.columns

Out[245]:
Index(['1', '2', '3'], dtype='object')

np.arange 当然有效,但您也可以只使用 list 理解:

df.columns = [i for i in range(len(df.columns))]

如果您希望将它们作为字符串,请使用 [str(i) for i in range(len(df.columns))]