How do I retrieve the number of columns in a Pandas data frame?
How do you programmatically retrieve the number of columns in a pandas dataframe? I was hoping for something like:
df.num_columns
Solution 1:
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
Solution 2:
Alternative:
df.shape[1]
(df.shape[0]
is the number of rows)
Solution 3:
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
Solution 4:
Surprised I haven't seen this yet, so without further ado, here is:
df.columns.size
Solution 5:
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