---
description: In this tutorial, we will learn about the Pandas read_csv() Method and groupby() Method to Import and Read CSV data in Pandas with Examples.
title: Pandas read_csv() in Python with Example
image: https://www.guru99.com/images/pandas-read-csv-1.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Pandas read\_csv() turns a comma-separated file, local or remote, into a DataFrame in a single call. This walkthrough imports the UCI adult census dataset, names its fifteen columns, and summarises the result with groupby aggregations.

* 🔘 **One call:** pd.read\_csv() accepts a file path, a URL, or any object exposing a read method.
* ☑️ **Column control:** Pass names to label the columns and index\_col=False to keep a plain integer index.
* ✅ **Whitespace:** skipinitialspace=True strips the space that follows every comma in the adult dataset.
* 🧪 **Group and aggregate:** groupby() summarises the frame with count, min, max, mean, median or std.
* 🛠️ **Large files:** usecols, dtype and chunksize cut parse time and memory on multi-gigabyte exports.
* ⚠️ **Common errors:** Encoding, bad lines and mixed dtypes each have a documented argument that fixes them.

[ Read More ](javascript:void%280%29;) 

![Pandas read_csv\(\) with Example](https://www.guru99.com/images/pandas-read-csv-1.png) 

## Import CSV in Pandas

During the TensorFlow tutorial, you will use the [adult dataset](https://archive.ics.uci.edu/dataset/2/adult), which is often used for classification tasks. The file used below is the raw `adult.data` export from the UCI Machine Learning Repository, and the dataset page also offers a zipped download and the `ucimlrepo` package if the direct path ever stops resolving.

The data is stored in CSV format. The dataset includes 8 categorical variables:

* workclass
* education
* marital
* occupation
* relationship
* race
* sex
* native\_country

And 6 continuous variables:

* age
* fnlwgt
* education\_num
* capital\_gain
* capital\_loss
* hours\_week

Together with the income `label` column, that makes the 15 column names you will pass to [Pandas](https://www.guru99.com/python-pandas-tutorial.html) in the next section.

## Pandas read\_csv() Method

To import a CSV dataset, you can use the object pd.read\_csv(). The basic signature is:

### Pandas read\_csv() Syntax

pandas.read_csv(filepath_or_buffer, sep=',', names=None, index_col=None, skipinitialspace=False)

* **filepath\_or\_buffer**: path, URL, or file-like object holding the data
* **sep=’,’**: the delimiter to use
* **names=None**: name the columns. If the dataset has ten columns, you need to pass ten names
* **index\_col=None**: which column to use as the row index. Pass False to force a fresh integer index
* **skipinitialspace=False**: skip spaces after the delimiter

For the full list of arguments, check the official [pandas.read\_csv() documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read%5Fcsv.html).

### Pandas read\_csv() Example

The snippet below names all 15 columns, points at the UCI file, and strips the space that follows every comma in this particular dataset.

## Import csv
import pandas as pd
## Define path data
COLUMNS = ['age','workclass', 'fnlwgt', 'education', 'education_num', 'marital',
           'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss',
           'hours_week', 'native_country', 'label']
PATH = "https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"
df_train = pd.read_csv(PATH,
                       skipinitialspace=True,
                       names = COLUMNS,
                       index_col=False)
df_train.shape

**Output:**

(32561, 15)

The shape confirms 32,561 rows and 15 columns, so every name in COLUMNS was matched to a field in the file.

### RELATED ARTICLES

* [TensorBoard Tutorial: TensorFlow Graph Visualization ](https://www.guru99.com/tensorboard-tutorial.html "TensorBoard Tutorial: TensorFlow Graph Visualization")
* [RNN (Recurrent Neural Network) Tutorial: TensorFlow Example ](https://www.guru99.com/rnn-tutorial.html "RNN (Recurrent Neural Network) Tutorial: TensorFlow Example")
* [11 BEST TensorFlow Books (2026 Update) ](https://www.guru99.com/best-tensorflow-books.html "11 BEST TensorFlow Books (2026 Update)")
* [Pandas Cheat Sheet for Data Science in Python ](https://www.guru99.com/pandas-cheat-sheet-for-data-science.html "Pandas Cheat Sheet for Data Science in Python")

## Key Pandas read\_csv() Parameters

read\_csv() accepts more than fifty arguments, but a small group covers almost every real import. The defaults below are the ones documented in the current pandas API reference.

| **Parameter**    | **Default** | **What it does**                                                                        |
| ---------------- | ----------- | --------------------------------------------------------------------------------------- |
| sep              | ‘,’         | Character or regex used as the delimiter. Use sep=’;’ or sep=’\\t’ for other formats.   |
| header           | ‘infer’     | Row number holding the column labels. Pass header=None when the file has no header row. |
| names            | not set     | Explicit list of column labels. Combine with header=0 to replace an existing header.    |
| index\_col       | None        | Column to use as the row index. index\_col=False forces a plain integer index.          |
| usecols          | None        | Subset of columns to load, by label or position. Cuts both parse time and memory.       |
| dtype            | None        | Per-column data types, for example {‘age’: ‘int32’}. Skips type inference.              |
| na\_values       | None        | Extra strings to read as NaN, such as the ‘?’ placeholder in the adult dataset.         |
| skiprows / nrows | None        | Skip leading lines, or read only the first N data rows.                                 |
| parse\_dates     | None        | Columns to convert to datetime while reading, paired with date\_format.                 |
| encoding         | ‘utf-8’     | Text encoding of the file. Use ‘latin-1’ or ‘cp1252’ for legacy exports.                |
| chunksize        | None        | Return an iterator that yields the file in blocks of N rows.                            |
| on\_bad\_lines   | ‘error’     | What to do with malformed rows: raise, warn, or skip them.                              |

Two of these deserve a note. `index_col=False` is not the same as leaving it unset: it explicitly tells Pandas not to promote the first column, which is what you want when a file ends every line with a stray delimiter. And `names` silently overwrites whatever the file declares, so pass `header=0` alongside it when the CSV really does carry a header row.

## Pandas groupby() Method

An easy way to see the data is to use the groupby method. This method can help you summarize the data by group. Below is a list of aggregations available with the groupby() method:

* count: count
* min: min
* max: max
* mean: mean
* median: median
* standard deviation: std
* and others

Inside groupby(), you name the column you want to group on before applying the aggregation.

Let us have a look at a single grouping with the adult dataset. You will get the mean of all the continuous variables by type of revenue, that is above 50k or below 50k:

df_train.groupby(['label']).mean()

| label | age       | fnlwgt       | education\_num | capital\_gain | capital\_loss | hours\_week |
| ----- | --------- | ------------ | -------------- | ------------- | ------------- | ----------- |
| <=50K | 36.783738 | 190340.86517 | 9.595065       | 148.752468    | 53.142921     | 38.840210   |
| \>50K | 44.249841 | 188005.00000 | 11.611657      | 4006.142456   | 195.001530    | 45.473026   |

You can get the minimum age by type of household:

df_train.groupby(['label'])['age'].min()
label
<=50K    17
>50K     19
Name: age, dtype: int64

You can also group by multiple columns. For instance, you can get the maximum capital gain according to the household type and marital status.

df_train.groupby(['label', 'marital'])['capital_gain'].max()
label  marital
<=50K  Divorced                 34095
       Married-AF-spouse         2653
       Married-civ-spouse       41310
       Married-spouse-absent     6849
       Never-married            34095
       Separated                 7443
       Widowed                   6849
>50K   Divorced                 99999
       Married-AF-spouse         7298
       Married-civ-spouse       99999
       Married-spouse-absent    99999
       Never-married            99999
       Separated                99999
       Widowed                  99999
Name: capital_gain, dtype: int64

You can create a plot after a groupby. One way to do it is to plot the grouped result directly.

To create a clearer plot, apply unstack() after mean() so the marital status moves from the index into the columns. The chart then has two groups, one per income label, instead of the fourteen (2\*7) bars a flat multilevel index would produce.

If you use a [Jupyter Notebook](https://www.guru99.com/jupyter-notebook-tutorial.html), remember to add %matplotlib inline, otherwise no plot will be displayed.

%matplotlib inline
df_plot = df_train.groupby(['label', 'marital'])['capital_gain'].mean().unstack()
df_plot

Plotting that unstacked frame as a bar chart gives the figure below.

[](https://www.guru99.com/images/tensorflow/082918%5F0617%5FPandasTutor2.png)

## How to Read Large CSV Files with Pandas

The adult dataset is small, but the same call can stall on a multi-gigabyte export. Three arguments do most of the work.

* **usecols** loads only the columns you actually need. The pandas documentation notes that this results in much faster parsing and lower memory usage.
* **dtype** pins each column to a type, so Pandas skips inference and does not widen integers to 64-bit by default.
* **chunksize** returns a TextFileReader instead of a DataFrame, letting you loop over blocks of N rows and aggregate as you go.

import pandas as pd

# read only the columns you need, with explicit types
cols  = ['age', 'education', 'capital_gain', 'label']
types = {'age': 'int32', 'capital_gain': 'int32'}
df = pd.read_csv(PATH, names=COLUMNS, usecols=cols, dtype=types,
                 skipinitialspace=True, index_col=False)

# stream the file in fixed-size chunks instead of loading it whole
total = 0
for chunk in pd.read_csv(PATH, names=COLUMNS, chunksize=10000,
                         skipinitialspace=True, index_col=False):
    total = total + len(chunk)
print(total)

Two further options help once the basics are in place. `engine='pyarrow'` switches to the multithreaded Arrow parser, and `dtype_backend='pyarrow'` keeps the result in Arrow-backed columns. `low_memory` is True by default, which parses the file internally in pieces, but it can produce mixed types in a column; set an explicit dtype rather than relying on it.

Finally, `compression='infer'` means a path ending in .gz, .zip, .bz2, .xz or .zst is decompressed on the fly, so there is no need to unpack an archive before reading it.

## Common Pandas read\_csv() Errors and How to Fix Them

Most read\_csv() failures come from four causes, and each has a documented argument that resolves it.

| **Error**                              | **Cause**                                                               | **Fix**                                                                              |
| -------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| FileNotFoundError                      | The path is relative to the working directory, not to the script.       | Use an absolute path, or confirm the URL scheme is one of http, ftp, s3, gs or file. |
| UnicodeDecodeError                     | The file is not UTF-8, which is the default encoding.                   | Pass encoding=’latin-1′ or the correct codec, or encoding\_errors=’replace’.         |
| ParserError: Error tokenizing data     | A row carries more fields than the header declares.                     | Pass on\_bad\_lines=’skip’ or ‘warn’, or set the correct sep.                        |
| DtypeWarning: columns have mixed types | Chunked type inference saw different types in one column.               | Set an explicit dtype, or low\_memory=False.                                         |
| Columns shifted by one                 | A trailing delimiter makes Pandas promote the first field to the index. | Pass index\_col=False.                                                               |

The adult dataset shows the missing-value case directly: unknown workclass, occupation and native\_country entries are stored as a literal question mark, so they arrive as the string ‘?’ unless you declare them.

# tolerate rows with too many fields instead of raising
df = pd.read_csv(PATH, names=COLUMNS, on_bad_lines='skip')

# read a file that is not UTF-8
df = pd.read_csv('sales.csv', encoding='latin-1')

# treat the dataset's '?' placeholder as a missing value
df = pd.read_csv(PATH, names=COLUMNS, na_values='?', skipinitialspace=True)

## FAQs

⚡ What is the difference between read\_csv() and read\_table()?

Both call the same parser. read\_csv() defaults to a comma delimiter, while read\_table() reads a general delimited file and expects you to set sep yourself. Use read\_csv() for comma files and read\_table() for tab or pipe separated exports.

💾 How do you write a DataFrame back to a CSV file?

Call df.to\_csv(‘output.csv’, index=False). Dropping the index avoids an unnamed first column on the next read. Add sep, encoding or compression arguments to mirror whatever settings you used when the file was imported.

📅 How do you parse date columns while reading a CSV?

Pass parse\_dates with the column names or positions, and add date\_format when the layout is not ISO 8601, for example date\_format=’%d/%m/%Y’. Without it, date columns arrive as plain object strings and need a separate to\_datetime call.

🔤 How do you read a CSV that uses a different delimiter?

Set sep to the character, such as sep=’;’ or sep=’\\t’. Separators longer than one character are treated as regular expressions and force the slower Python engine. sep=None lets that engine sniff the delimiter from the first valid row.

📉 How do you read only part of a very large CSV?

Use nrows to cap the number of data rows returned, and skiprows to jump past a block of leading lines. Combining them pages through a file, for example skiprows=1000000 with nrows=999999 to read the second million rows.

🗜️ Can read\_csv() open compressed or remote files?

Yes. compression defaults to ‘infer’, so a path ending in .gz, .zip, .bz2, .xz or .zst is decompressed automatically. URLs using http, ftp, s3, gs or file all work, and storage\_options passes credentials to the remote backend.

🤖 How does machine learning help clean messy CSV data?

Trained models flag likely type errors, cluster near-duplicate category spellings, and impute missing values from the surrounding columns. That narrows the manual cleanup to the rows a rule-based na\_values or dtype setting cannot resolve on its own.

🛠️ Can GitHub Copilot generate the right read\_csv arguments?

Copilot drafts the boilerplate quickly once it can see a sample of the file. Treat the argument list as a draft, because it often guesses dtype and encoding. Check every generated keyword against the pandas API reference before running it.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/pandas-read-csv-1.png","url":"https://www.guru99.com/images/pandas-read-csv-1.png","width":"700","height":"250","caption":"Pandas read_csv()","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/pandas-read-csv.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/tensorflow","name":"TensorFlow"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/pandas-read-csv.html","name":"Pandas read_csv() in Python with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/pandas-read-csv.html#webpage","url":"https://www.guru99.com/pandas-read-csv.html","name":"Pandas read_csv() in Python with Example","dateModified":"2026-07-27T17:29:47+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/pandas-read-csv-1.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/pandas-read-csv.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/evelyn","name":"Evelyn Clarke","description":"I'm Evelyn Clarke, an AI Research Scientist specializing in machine learning and natural language processing, dedicated to advancing the field responsibly.","url":"https://www.guru99.com/author/evelyn","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/evelyn-clarke-author-120x120.png","url":"https://www.guru99.com/images/evelyn-clarke-author-120x120.png","caption":"Evelyn Clarke","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"TensorFlow","headline":"Pandas read_csv() in Python with Example","description":"In this tutorial, we will learn about the Pandas read_csv() Method and groupby() Method to Import and Read CSV data in Pandas with Examples.","keywords":"tensorflow, Data Warehousing, Tableau","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/evelyn","name":"Evelyn Clarke"},"dateModified":"2026-07-27T17:29:47+05:30","image":{"@id":"https://www.guru99.com/images/pandas-read-csv-1.png"},"copyrightYear":"2026","name":"Pandas read_csv() in Python with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between read_csv() and read_table()?","acceptedAnswer":{"@type":"Answer","text":"Both call the same parser. read_csv() defaults to a comma delimiter, while read_table() reads a general delimited file and expects you to set sep yourself. Use read_csv() for comma files and read_table() for tab or pipe separated exports."}},{"@type":"Question","name":"How do you write a DataFrame back to a CSV file?","acceptedAnswer":{"@type":"Answer","text":"Call df.to_csv('output.csv', index=False). Dropping the index avoids an unnamed first column on the next read. Add sep, encoding or compression arguments to mirror whatever settings you used when the file was imported."}},{"@type":"Question","name":"How do you parse date columns while reading a CSV?","acceptedAnswer":{"@type":"Answer","text":"Pass parse_dates with the column names or positions, and add date_format when the layout is not ISO 8601, for example date_format='Y'. Without it, date columns arrive as plain object strings and need a separate to_datetime call."}},{"@type":"Question","name":"How do you read a CSV that uses a different delimiter?","acceptedAnswer":{"@type":"Answer","text":"Set sep to the character, such as sep=';' or sep='t'. Separators longer than one character are treated as regular expressions and force the slower Python engine. sep=None lets that engine sniff the delimiter from the first valid row."}},{"@type":"Question","name":"How do you read only part of a very large CSV?","acceptedAnswer":{"@type":"Answer","text":"Use nrows to cap the number of data rows returned, and skiprows to jump past a block of leading lines. Combining them pages through a file, for example skiprows=1000000 with nrows=999999 to read the second million rows."}},{"@type":"Question","name":"Can read_csv() open compressed or remote files?","acceptedAnswer":{"@type":"Answer","text":"Yes. compression defaults to 'infer', so a path ending in .gz, .zip, .bz2, .xz or .zst is decompressed automatically. URLs using http, ftp, s3, gs or file all work, and storage_options passes credentials to the remote backend."}},{"@type":"Question","name":"How does machine learning help clean messy CSV data?","acceptedAnswer":{"@type":"Answer","text":"Trained models flag likely type errors, cluster near-duplicate category spellings, and impute missing values from the surrounding columns. That narrows the manual cleanup to the rows a rule-based na_values or dtype setting cannot resolve on its own."}},{"@type":"Question","name":"Can GitHub Copilot generate the right read_csv arguments?","acceptedAnswer":{"@type":"Answer","text":"Copilot drafts the boilerplate quickly once it can see a sample of the file. Treat the argument list as a draft, because it often guesses dtype and encoding. Check every generated keyword against the pandas API reference before running it."}}]}],"@id":"https://www.guru99.com/pandas-read-csv.html#schema-1152353","isPartOf":{"@id":"https://www.guru99.com/pandas-read-csv.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/pandas-read-csv.html#webpage"}}]}
```
