The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life

--

Chapters
00:00 How Do I Retrieve The Number Of Columns In A Pandas Data Frame?
00:17 Accepted Answer Score 412
00:27 Answer 2 Score 136
00:39 Answer 3 Score 37
00:59 Answer 4 Score 1
01:16 Thank you

--

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

--

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