0

I am trying to create a pandas df like this post.

enter image description here

df = pd.DataFrame(np.arange(9).reshape(3,3) , columns=list('123'))
df

this piece of code gives

enter image description here

describe() gives

enter image description here

is there is way to set the name of each row (i.e. the index) in df as 'A', 'B', 'C' instead of '0', '1', '2' ?

2 Answers2

0

Use df.index:

df.index=['A', 'B', 'C']

print(df)
   1  2  3
A  0  1  2
B  3  4  5
C  6  7  8

A more scalable and general solution would be using list-comprehension

df.index = [chr(ord('a') + x).upper() for x in df.index]

print(df)
   1  2  3
A  0  1  2
B  3  4  5
C  6  7  8
Erfan
  • 40,971
  • 8
  • 66
  • 78
0

Add index parameter in DataFrame constructor:

df = pd.DataFrame(np.arange(9).reshape(3,3) , 
                  index=list('ABC'),
                  columns=list('123'))
print (df)
   1  2  3
A  0  1  2
B  3  4  5
C  6  7  8
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252