The Python Oracle

How do I retrieve the number of columns in a Pandas data frame?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Question
00:21 Accepted answer (Score 397)
00:34 Answer 2 (Score 131)
00:50 Answer 3 (Score 34)
01:16 Answer 4 (Score 5)
01:33 Thank you

--

Full question
https://stackoverflow.com/questions/2029...

Answer 3 links:
[df.columns.size]: https://pandas.pydata.org/pandas-docs/st...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #dataframe

#avk47



ACCEPTED ANSWER

Score 412


Like so:

import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

len(df.columns)
3



ANSWER 2

Score 136


Alternative:

df.shape[1]

(df.shape[0] is the number of rows)




ANSWER 3

Score 37


If the variable holding the dataframe is called df, then:

len(df.columns)

gives the number of columns.

And for those who want the number of rows:

len(df.index)

For a tuple containing the number of both rows and columns:

df.shape



ANSWER 4

Score 1


df.info() function will give you result something like as below. If you are using read_csv method of Pandas without sep parameter or sep with ",".

raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age