Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas show column number

Tags:

python

pandas

is there any way to get pandas to show the column number and the column name at the same time? I'm dealing with a dataset with >30 columns, all of very long column names and some with little variation with each other. Its an absolute chore to type out the names when writing out the code. (i would still need to see the column names to know which columns to select)

thanks.

like image 771
rabbito Avatar asked Jan 23 '26 14:01

rabbito


1 Answers

One possible solution is create MultiIndex and then select columns by DataFrame.xs:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

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

df.columns = pd.MultiIndex.from_arrays([pd.RangeIndex(len(df.columns)), df.columns])
print (df)
   0  1  2  3  4  5
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

print (df.xs(2, level=0, axis=1))
   C
0  7
1  8
2  9
like image 78
jezrael Avatar answered Jan 26 '26 08:01

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!