An economist An economist - 11 months ago 50
Python Question

How to rename only 'Unnamed:' columns as numeric index

I am reading excel file as a

data frame
. However, first three of my columns have headers and the rest need just an numeric index. When I read the file in I get output below.

a b c Unnamed: 4 Unnamed: 5 Unnamed: 6
0 0.109066 -1.112704 -0.545209 0.109066 -1.112704 -0.545209
1 0.447114 1.525341 0.317252 0.109066 -1.112704 -0.545209
2 0.507495 0.137863 0.886283 1.452867 1.888363 1.168101
3 1.452867 1.888363 1.168101 0.901371 -0.704805 0.088335
4 0.901371 -0.704805 0.088335 0.901371 -0.704805 0.088335


I would like to have data frame looking like this, keeping in mind that number of unnamed columns could vary.

a b c 1 2 3
0 0.109066 -1.112704 -0.545209 0.109066 -1.112704 -0.545209
1 0.447114 1.525341 0.317252 0.109066 -1.112704 -0.545209
2 0.507495 0.137863 0.886283 1.452867 1.888363 1.168101
3 1.452867 1.888363 1.168101 0.901371 -0.704805 0.088335
4 0.901371 -0.704805 0.088335 0.901371 -0.704805 0.088335


How could I rename all of the
Unnamed: #
columns and assign them numeric index?

Answer Source

I don't think you should hardcode your mappings. Use a list comprehension.

In [550]: i = iter(range(1, len(df.columns) + 1))

In [551]: df.columns = [x if not x.startswith('Unnamed') else next(i) for x in df.columns]

In [552]: df
Out[552]: 
          a         b         c         1         2         3
0  0.109066 -1.112704 -0.545209  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252  0.109066 -1.112704 -0.545209
2  0.507495  0.137863  0.886283  1.452867  1.888363  1.168101
3  1.452867  1.888363  1.168101  0.901371 -0.704805  0.088335
4  0.901371 -0.704805  0.088335  0.901371 -0.704805  0.088335
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download