Korzak
Korzak

Reputation: 385

Can't set column name from index to str(index) + string (Pandas, Python)

I need to change the names of a subset of columns in a dataframe from whatever number they are to that number plus a string suffix. I know there is a function to add a suffix, but it doesn't seem to work on just indices.

I create a list with all the column indices in it, then run a loop that, for each item in that list, it renames the dataframe column that matches the list item to the same number, plus the suffix string.

        if scalename == "CDR":
        print(scaledf.columns.tolist())
        oldCols = scaledf.columns[7:].tolist()
        for f in range(len(oldCols)):
            changeCol = int(oldCols[f])
            print(changeCol)
            scaledf.rename(columns = {changeCol:scalename + str(changeCol)})
        print(scaledf.columns)

This doesn't work.

The code will print out the column names, and prints out every item, but it does not rename the columns. It doesn't throw errors, it just doesn't work. I've tried variation after variation, and gotten all kinds of other errors, but this error-free code does nothing. It just runs, and doesn't rename anything.

Any help would be seriously appreciated! Thank you.


Adding sample of list:

45
52
54
55
59
60
61
66
67
68
69
73
74
75
80
81
82
94
101
103
104
108
110
115
116
117
129
136
138
139
143
144
145
150
151
157
158
159
171
178
180
181
185
186
187
192
193
199
200
201
213
220
222
223
227
228
229
234
235
236

Upvotes: 0

Views: 165

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

Try this:

scaledf = scaledf.rename(columns=lambda c:scalename + str(c) if c in oldCols else c)

Upvotes: 1

Related Questions