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,
CodePudding user response:
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'
CodePudding user response:
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.