Eric Baldwin
Eric Baldwin

Reputation: 3501

How can I refer to a column with a number as its name in a pandas dataframe?

I created a square dataframe in which the columns' names are its indices. See below for an example:

matrix
Out[75]: 
      24787 24798 24799 24789 24790 24791 24793 24797 24794 24796 24795 24788
24787   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
24798   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
24799   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
24789   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
24790   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
24791   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
...

I want to refer to each column, but matrix['24787'] returns KeyError: '24787' and matrix.24787 returns SyntaxError: invalid syntax. How do I refer to my column?

Upvotes: 1

Views: 1719

Answers (1)

Alex Riley
Alex Riley

Reputation: 176978

If the column names are integers (not strings), you can select a specific column with the specific integer value:

matrix[24787]

or, using the loc label selector,

matrix.loc[:, 24787]

If you want to select by index number, you can use iloc. For example, matrix.iloc[:, 0] selects the first column.

Upvotes: 2

Related Questions