Home > Blockchain >  Indexing while using pandas loc
Indexing while using pandas loc

Time:10-14

I have a pd.DataFrame which had a Datetime index. When I select a particular Datetime and when there are two matches, it correctly selects date as the index.

a = df.loc[date] a Symbol Order Shares Date
2011-01-10 AAPL BUY 1500 2011-01-10 AAPL SELL 1500

However, when there is only one match for that date, it assigns the columns as the index.

orders Symbol GOOG Order BUY Shares 1000 Name: 2011-01-26 00:00:00, dtype: object

How can I force it to take Date as the index all the time? I don't have a name for the index.

CodePudding user response:

You can use one element list:

a = df.loc[[date]]

Sample:

print (df)
         Symbol Order  Shares
Date                           
2011-01-09   AAPL   BUY    1500
2011-01-10   AAPL   BUY    1500
2011-01-10   AAPL  SELL    1500

date = '2011-01-09'
a = df.loc[[date]]
print (a)
           Symbol Order  Shares
Date                           
2011-01-09   AAPL   BUY    1500

date = '2011-01-10'
a = df.loc[[date]]
print (a)
           Symbol Order  Shares
Date                           
2011-01-10   AAPL   BUY    1500
2011-01-10   AAPL  SELL    1500
  • Related