Py学习  »  Python

在python中,如何将列从unnamed:0重命名为带递增数的列

ZH Law • 4 年前 • 1351 次点击  

Df之前:

    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

对测向仪来说是这样的:

     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')
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51181
 
1351 次点击  
文章 [ 5 ]  |  最新文章 4 年前
oppressionslayer
Reply   •   1 楼
oppressionslayer    4 年前

df.rename(lambda x: x.replace('unnamed:', 't'), axis=1) 

输出:

     t0       t1       t2
0   Megan  30000   Botany
1   Ann    24000   Psychology
2   John   24000   Police
3   Mary   45000   Genetics
4   Jay    60000   Data Science
RafaelC
Reply   •   2 楼
RafaelC    4 年前

你的数据已经在增加。你只是想 t 而不是 unnamed: 作为前缀。

df.columns = df.columns.str.replace('unnamed:', 't')
Andy L.
Reply   •   3 楼
Andy L.    4 年前

尝试 rename 有弦的 split

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 arange np.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))
Nicolas Gervais
Reply   •   4 楼
Nicolas Gervais    4 年前

这将从0到您拥有的列数

testfile.columns = ['t{}'.format(i) for i in range(testfile.shape[1])]
AdibP
Reply   •   5 楼
AdibP    4 年前

您可以使用此选项重置列名并为其添加前缀

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