How can I skip even/odd rows while reading a csv file?

Viewed 1539

Is there a simple way to ignore all even/odd rows when reading a csv using pandas?

I know skiprows argument in pd.read_csv but for that I'll need to know the number of rows in advance.

2 Answers

The pd.read_csv skiprows argument accepts a callable, so you could use a lambda function. E.g.:

df = pd.read_csv(some_path, skiprows=lambda x: x%2 == 0)

A possible solution after reading would be:

import pandas as pd
df = pd.read_csv(some_path)
# remove odd rows:
df = df.iloc[::2]
# remove even rows:
df = df.iloc[1::2]
Related