How to load only column names from csv file (Pandas)?

I have a large csv file and I don't want to load it completely into my memory, I only need to get the column names from this csv file. How do I download it?

+3


source to share


2 answers


try this:



pd.read_csv(file_name, nrows=1).columns.tolist()

      

+3


source


If you pass nrows=0

before read_csv

then it will only load the column row:

In[8]:
import pandas as pd
import io
t="""a,b,c,d
0,1,2,3"""
pd.read_csv(io.StringIO(t), nrows=0)

Out[8]: 
Empty DataFrame
Columns: [a, b, c, d]
Index: []

      



Then access to the attribute .columns

will give you the columns:

In[10]:
pd.read_csv(io.StringIO(t), nrows=0).columns

Out[10]: Index(['a', 'b', 'c', 'd'], dtype='object')

      

+4


source







All Articles