renaming columns of a pd.DataFrame using np.arange or something else within pd.<function> to assign alphabets

Question:

I’m using python 3.9. My pd.DataFrame has 11 columns which are numbered as (by default)

Col names –> 0 1 2 3 4 5 6 7 8 9 10

Can I use np.arange or pd.array() or someother function within pandas to assign/change the column names to alphabets?

I know long solution is :
df = pd.DataFrame(input_data,columns=[‘A’,’B’,’C’,’D’,’E’,’F’,’G’,’H’,’I’,’J’,’K’])

I was wondering if some function/method like columns=np.arange(‘A’,’J’) would be possible. From running this code I learned arange can only handle int and floats not strings. Is there any object function that can accomplish this?

BRgds,

Asked By: Python_Infant

||

Answers:

import pandas as pd
import numpy as np

input_data = np.random.random((100, 11))
cols = [chr(65 + c) for c in range(input_data.shape[1])]
df = pd.DataFrame(input_data, columns=cols)
print(df)

prints

index A B C D E F G H I J K
0 0.9754801564654546 0.9803147001267726 0.7301867551168492 0.34014130872203274 0.9030310266294121 0.019942427424042175 0.8876547248004468 0.7566170681794626 0.7544506461801366 0.8322020013684206 0.3540067814406911

Explanation: chr(i) returns the character corresponding to the i-th unicode, and 'A' is the 65-th (i.e. (65 + 0)th) unicode, 'B' the 66-th (i.e. (65 + 1)th), etc.

Answered By: Michael Hodel

You can use string.ascii_uppercase:

from string import ascii_uppercase as ABC
import pandas as pd

df = pd.DataFrame(data)
df.columns = list(ABC)[:len(df.columns)]

# >>> ABC
# 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Answered By: Rodalm
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.