Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas KeyError when using .loc() [duplicate]

I have a pandas DataFrame portfolio whose keys are dates. I'm trying to access multiple rows through

print(portfolio.loc[['2007-02-26','2008-02-06'],:]),

but am getting an error

KeyError: "None of [Index(['2007-02-26', '2008-02-06'], dtype='object', name='Date')] are in the [index]"

However, print(portfolio.loc['2007-02-26',:]) successfully returns

holdings      1094.6124
pos_diff       100.0000
cash         98905.3876
total       100000.0000
returns          0.0000
Name: 2007-02-26 00:00:00, dtype: float64

Isn't this a valid format--> df.loc[['key1', 'key2', 'key3'], 'Column1]?

like image 711
Marco Deicas Avatar asked Sep 12 '25 23:09

Marco Deicas


1 Answers

It seems that the issue is with type conversion from strings to timestamps. The solution is, therefore, to explicitly convert the set of labels to DateTime before passing them to loc:

df = pd.DataFrame({"a" : range(5)}, index = pd.date_range("2020-01-01", freq="1D", periods=5))
print(df) 

==> 
            a
2020-01-01  0
2020-01-02  1
2020-01-03  2
2020-01-04  3
2020-01-05  4

try:
    df.loc[["2020-01-01", "2020-01-02"], :]    
except Exception as e:
    print (e) 

 ==>
"None of [Index(['2020-01-01', '2020-01-02'], dtype='object')] are in the [index]"

# But - if you convert the labels to datetime before calling loc, 
# it works fine. 
df.loc[pd.to_datetime(["2020-01-01", "2020-01-02"]), :]

===>
            a
2020-01-01  0
2020-01-02  1
like image 180
Roy2012 Avatar answered Sep 14 '25 13:09

Roy2012