如何在Python中使用数字重命名多个列?

3
我有一个数据框,大约有2400个列,我想把所有的列从12400重命名。 我当前的列名是数字,几乎所有的数字都是重复的。
我尝试过像这样的操作,但它不起作用:
# 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)

提前感谢你的帮助。


这是 C# 代码吗? - KernelPanic
不,这是Python代码。 - roune_67
1
你的示例不完整 - 它没有定义 pd。你应该[编辑]你的问题,以便有一个 [mcve]。这可能使别人能够重现你的工作并提出解决方案。 - Toby Speight
我说这里的列是“指挥官”、“日期”和“分数”,对吗? - Vasili Syrakis
是的。但这只是一个例子。在我的实际数据中,列名是数字。 - roune_67
2个回答

1

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')

pd.Index(np.arange(1,len(df.columns)+1)).astype(str) - roune_67
这正是我在寻找的!非常感谢 @EdChum - roune_67

1

np.arange 肯定可行,但你也可以使用 list 推导式:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接