如何从中重命名列未命名:0到python中具有递增编号的列

2024-05-19 20:27:43 发布

您现在位置:Python中文网/ 问答频道 /正文

前测向:

    unnamed:0   unnamed:1  unnamed:2
0   Megan       30000      Botany
1   Ann         24000      Psychology
2   John        24000      Police
3   Mary        45000      Genetics
4   Jay         60000      Data Science

对于df,如下所示:

     t0       t1       t2
0   Megan  30000   Botany
1   Ann    24000   Psychology
2   John   24000   Police
3   Mary   45000   Genetics
4   Jay    60000   Data Science

我已尝试重命名未命名的列:

testfile.columns = testfile.columns.str.replace('Unnamed.*', 't')
testfile = testfile.rename(columns=lambda x: x+'x')

Tags: columnsdfdatajohnsciencemaryanntestfile
3条回答

这将从0到您拥有的列数

testfile.columns = ['t{}'.format(i) for i in range(testfile.shape[1])]

您可以使用它来重置列名并为它们添加前缀

df = df.T.reset_index(drop=True).T.add_prefix('t')
      t0     t1            t2
0  Megan  30000        Botany
1    Ann  24000    Psychology
2   John  24000        Police
3   Mary  45000      Genetics
4    Jay  60000  Data Science

用字符串split尝试rename

df = df.rename(lambda x: 't'+x.split(':')[-1], axis=1)

Out[502]:
      t0     t1           t2
0  Megan  30000       Botany
1    Ann  24000   Psychology
2   John  24000       Police
3   Mary  45000     Genetics
4    Jay  60000  DataScience

如果您不关心unnamed:X中的数字,只需要t上的增量,可以使用numpy arangenp.char.add来构造它们

np.char.add('t', np.arange(df.shape[1]).astype(str))
array(['t0', 't1', 't2'], dtype='<U12')

将其直接指定给列

df.columns = np.char.add('t', np.arange(df.shape[1]).astype(str))

相关问题 更多 >