【问题标题】:How can I rename multiple columns with numbers in python?如何在python中用数字重命名多个列?
【发布时间】:2016-10-08 15:43:30
【问题描述】:

我有一个包含 ~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)

提前谢谢你。

【问题讨论】:

  • 这是C# 代码吗?
  • 不,是 Python 代码
  • 您的示例不完整 - 它没有定义 pd。你应该edit你的问题有一个minimal reproducible example。这可能使某人能够复制您的工作并提出解决方案。
  • 我说这里的列是“指挥官”、“日期”和“分数”对吗?
  • 是的。但这只是一个例子。在我的真实数据中,列名是数字。

标签: python dictionary pandas rename multiple-columns


【解决方案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)
  • 这正是我想要的!非常感谢@EdChum
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2023-01-10
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 2012-08-08
    • 2015-08-22
    • 2018-10-27
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多