'passing a string variable as and input to loc accessor in python

I am trying to pass a string variable (containing the parameter) to the .loc accessor but cannot get the syntax correct.

startenddate = "'2020-06':'2020-07'"
qf = cf.QuantFig(df = stock.data.loc[startenddate])

I get the error

ParserError: Unknown string format: '2020-06':'2020-07'

it works if I just plug in qf = cf.QuantFig(df = stock.data.loc['2020-06':'2020-07']) but I want to convert this into a function and pass starenddate as a parameter that us used in the .loc.



Solution 1:[1]

You can achieve the same by doing this:

start_date = '2020-06'
end_date = '2020-07'
data.loc[start_date:end_date]

You're passing a string into the .loc[] and then you expect it to match with the index.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prats