'Loading data from dataframes

Load other two DataFrames: g1900s, and g2000s. These contain the Gapminder life expectancy data for, respectively, the 19th century, the 20th century (1900-1999, starts from 263 row in gapminder.csv), and the 21st (2000-2016, starts from 523 row) century and 'Life expectancy' (as first column) each.

gapminder = pd.read_csv('gapminder.csv', index_col=0)
cols_g1900s = ['Life expectancy'] + list(gapminder.loc[:,'1900':'1999'])
g1900s = gapminder.loc[:, cols_g1900s]
print(g1900s.head())

That's code which I have for now shows everything like it should, the only thing that it shows only nan values.

DataFrame:

DATAFRAME

My bad result:

MY BAD RESULT

What I need:

WHAT I NEED

Probably I need to select ranges somehow but I don't know.



Solution 1:[1]

Try using .columns:

gapminder = pd.read_csv('gapminder.csv', index_col=0)
cols_g1900s = ['Life expectancy'] + list(gapminder.loc[:,'1900':'1999'].columns)
g1900s = gapminder.loc[:, cols_g1900s]
print(g1900s.head())

Solution 2:[2]

You can use filter to filter all the 19th century and then df.columns

cols_g1900s = ['Life expectancy'] + gapminderdf.filter(regex='^19').columns.tolist()
g1900s = gapminder[cols_g1900s]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CainĂ£ Max Couto-Silva
Solution 2