Search code examples
pythonpandasmatplotlibohlc

A string doesn't have the attribute .loc


I have different dataframes that follow the example: 'AAPLdf, AMZNdf, GOOGLdf, ...' etc I just want to be able to enter the ticker as an input so that I don't have write the same code a million times.

import matplotlib.pyplot as plt
from mpl_finance import candlestick_ohlc
import pandas as pd
import matplotlib.dates as mpl_dates
ticker = input("ticker:") + "df"
data = ticker
ohlc = data.loc[:, ['t', 'o', 'h', 'l', 'c']]

AttributeError: 'str' object has no attribute 'loc'


Solution

  • ticker = input('ticker: ')
    
    # this will return data as the dataframe from ticker, but it must be an exact match
    data = eval(f'{ticker}df')  # -> equivalent to eval('GOOGLdf`), for example
    
    # now you can use .loc 
    data.loc[:, :]