2017-10-18 65 views
0

我原來有多少個csv文件。用str +數字重命名特定列的數字

我創建了一個有9列的數據框,其中的r有數字作爲標題。

我只想定位它們並將其名稱更改爲['Apple'] +範圍(len(文件))。

例如: 我有3個csv文件。

在我的數據幀當前3個針對性的欄目有:

  0  1  2 
0  444.0 286.0 657.0 
1  2103.0 2317.0 2577.0 
2  157.0 200.0 161.0 
3  4000.0 3363.0 4986.0 
4  1042.0 541.0 872.0 
5  1607.0 1294.0 3305.0 

我想:

 Apple1 Apple2 Apple3 
0  444.0 286.0 657.0 
1  2103.0 2317.0 2577.0 
2  157.0 200.0 161.0 
3  4000.0 3363.0 4986.0 
4  1042.0 541.0 872.0 
5  1607.0 1294.0 3305.0 

謝謝

回答

1

IIUC,你可以初始化一個itertools.count對象並重置列在列表中理解。

from itertools import count 

cnt = count(1) 
df.columns = ['Apple{}'.format(next(cnt)) if 
     str(x).isdigit() else x for x in df.columns] 

這也將很好地工作,如果數字是不連續的,但你希望他們有一個連續的後綴改名:

print(df) 
     1 Col1  5 Col2  500 
0 1240.0 552.0 1238.0 52.0 1370.0 
1 633.0 435.0 177.0 2201.0 185.0 
2 1518.0 936.0 385.0 288.0 427.0 
3 212.0 660.0 320.0 438.0 1403.0 
4 15.0 556.0 501.0 1259.0 1298.0 
5 177.0 718.0 1420.0 833.0 984.0 

cnt = count(1) 
df.columns = ['Apple{}'.format(next(cnt)) if 
     str(x).isdigit() else x for x in df.columns] 

print(df) 
    Apple1 Col1 Apple2 Col2 Apple3 
0 1240.0 552.0 1238.0 52.0 1370.0 
1 633.0 435.0 177.0 2201.0 185.0 
2 1518.0 936.0 385.0 288.0 427.0 
3 212.0 660.0 320.0 438.0 1403.0 
4 15.0 556.0 501.0 1259.0 1298.0 
5 177.0 718.0 1420.0 833.0 984.0 
0

您可以使用rename_axis:

df.rename_axis(lambda x: 'Apple{}'.format(int(x)+1) if str(x).isdigit() else x, axis="columns") 
Out[9]: 
    Apple1 Apple2 Apple3 
0 444.0 286.0 657.0 
1 2103.0 2317.0 2577.0 
2 157.0 200.0 161.0 
3 4000.0 3363.0 4986.0 
4 1042.0 541.0 872.0 
5 1607.0 1294.0 3305.0