Yvar
Yvar

Reputation: 155

How can I store the index date (last row) from a panda dataframe in a variable?

I have a panda dataframe with the following rows and columns:

enter image description here

I need the date in the last row of the dataframe for plotting out a chart. How can I store the Date (see NAME:2021-01-29) in a variable?

I did trying

df1["Name:"].iloc[0]

But I get an error: KeyError: 'Name'

enter image description here

Upvotes: 0

Views: 245

Answers (2)

Lumber Jack
Lumber Jack

Reputation: 622

Your last index is

df1.index[-1]

You can store it in a variable.

If you want to get let's say the Open of this last index, you can just type

df1.Open[-1]

If you want to use the variable and filter it (or if it's not the last index):

var = df1.index[-1] # or another...
df1[df1.index==var].Open

Upvotes: 1

user15115588
user15115588

Reputation:

You can try this -

>>> data = [1,2,3,4,5,6]
>>> index = ['2020-01-01','2020-01-02','2020-01-03','2020-01-04','2020-01-05','2020-01-06']
>>> df = pd.DataFrame(data,index=index,columns=['Open'])
>>> df
            Open
2020-01-01     1
2020-01-02     2
2020-01-03     3
2020-01-04     4
2020-01-05     5
2020-01-06     6


### iloc[-1] returns as Series
### >>> type(df.iloc[-1])
### <class 'pandas.core.series.Series'>
>>> df.iloc[-1].name
'2020-01-06'

### iloc[-1] returns as DataFrame
### >>> type(df.iloc[[-1]])
### <class 'pandas.core.frame.DataFrame'>
>>> df.iloc[[-1]].index[0]
'2020-01-06'

Upvotes: 0

Related Questions