AK9309 AK9309 - 2 months ago 12
Python Question

Calling rows in a dataframe

Here is example code:

dates = pd.date_range('2005-01-01', periods=4)
A = [1,2,2,3]
B = [2,3,4,5]
df1 = pd.DataFrame({'A':A,'B':B},index = dates)
df1.loc['2005-01-04'].tolist()


It works just fine
Is there a way for me to give an integer 2 with a row index so it would give me a the row
2005-01-02


I have a 1000 row dataframe that I got with a for loop, and when I try to call a row in the same fashion it gives me an error saying that


label[] is not in the [index]


And that's the main problem that I can't figure out.

Any help would be appreciated.
Thanks!

Answer

You can use .ix to select the range of the DataFrame you are interested in.

By label:

df1.ix['2005-01-03':'2005-01-04']

By index number:

df1.ix[2:4]

Update based on comments

You can work out the integer index of the date using get_loc.

i = df1.index.get_loc('2005-01-04')
offset = 2
df1.ix[i-offset: i]