How to get even or odd rows in Pandas Dataframe?
There is a simple method without applying any function of filters.
import pandas as pd
df=pd.read_csv("http://bit.ly/drinksbycountry")
df.head()
| country | beer_servings | spirit_servings | wine_servings | total_litres_of_pure_alcohol | continent | |
|---|---|---|---|---|---|---|
| 0 | Afghanistan | 0 | 0 | 0 | 0.0 | Asia |
| 1 | Albania | 89 | 132 | 54 | 4.9 | Europe |
| 2 | Algeria | 25 | 0 | 14 | 0.7 | Africa |
| 3 | Andorra | 245 | 138 | 312 | 12.4 | Europe |
| 4 | Angola | 217 | 57 | 45 | 5.9 | Africa |
df.shape
(193, 6)
# Dataframe has 193 records, lets get only even rows without applying any filter.
df[::2].head(10)
| country | beer_servings | spirit_servings | wine_servings | total_litres_of_pure_alcohol | continent | |
|---|---|---|---|---|---|---|
| 0 | Afghanistan | 0 | 0 | 0 | 0.0 | Asia |
| 2 | Algeria | 25 | 0 | 14 | 0.7 | Africa |
| 4 | Angola | 217 | 57 | 45 | 5.9 | Africa |
| 6 | Argentina | 193 | 25 | 221 | 8.3 | South America |
| 8 | Australia | 261 | 72 | 212 | 10.4 | Oceania |
| 10 | Azerbaijan | 21 | 46 | 5 | 1.3 | Europe |
| 12 | Bahrain | 42 | 63 | 7 | 2.0 | Asia |
| 14 | Barbados | 143 | 173 | 36 | 6.3 | North America |
| 16 | Belgium | 295 | 84 | 212 | 10.5 | Europe |
| 18 | Benin | 34 | 4 | 13 | 1.1 | Africa |
# Lets see how to get odd rows.
df[['country','beer_servings','continent']][1::2].head(10)
| country | beer_servings | continent | |
|---|---|---|---|
| 1 | Albania | 89 | Europe |
| 3 | Andorra | 245 | Europe |
| 5 | Antigua & Barbuda | 102 | North America |
| 7 | Armenia | 21 | Europe |
| 9 | Austria | 279 | Europe |
| 11 | Bahamas | 122 | North America |
| 13 | Bangladesh | 0 | Asia |
| 15 | Belarus | 142 | Europe |
| 17 | Belize | 263 | North America |
| 19 | Bhutan | 23 | Asia |