简体   繁体   中英

How to access the second to last row of a csv file using python Pandas?

Want to know if I can access the second to last row of this csv file? Am able to access the very last using:

pd.DataFrame(file1.iloc[-1:,:].values)

But want to know how I can access the one right before the last?

Here is the code I have so far:

import pandas as pd
import csv


url1 = r"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/country_data/Austria.csv"

file1 = pd.read_csv(url1)

df1 = pd.DataFrame(file1.iloc[:,:].values)

df1 = pd.DataFrame(file1.iloc[-1:,:].values)


Austria_date = df1.iloc[:,1]

Austria_cum = df1.iloc[:, 4].map('{:,}'.format)


if ( Austria_cum.iloc[0] == 'nan' ):

Essentially I am checking if the the row at that specific col is 'nan', which is True, and after which I want to get the data from the row right before the last. Please, how would this be done?

Thank you

As simple as that:

df1.iloc[-2,:]

To access the data frame at any index you can use the following

df.iloc[i]

For your ask you need to set the index as -2, which would look like this:

df.iloc[-2]

Just use negative indices like in your example, but pull out the second to last with -2 instead of the last:

df.iloc[-2,:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM