C Cherniawski
C Cherniawski

Reputation: 3

How to reference the index column of a pandas dataframe in a function

I can't figure out how to get this code to run properly.

df1 = pd.read_csv('TradeSheet2.csv', engine='python', sep=r'\s*,\s*', index_col='Symbol', header=0, encoding='ascii')
buy_sig = df1.loc[df1.Total >= 20]
sell_sig = df1.loc[df1.Total <= -20]
df2 = pd.read_csv('Header_Col.csv', index_col='Symbol')

def create_long():
    global df2
    dfnewlong = pd.concat([df2, buy_sig]).drop_duplicates(keep=False)
    print(dfnewlong)
    print(dfnewlong.index)
    dfnewlong.set_index('Symbol', inplace=True, drop=False)
    dfnewlong['DateTime'] = pd.to_datetime(dfnewlong['DateTime'])
    dfnewlong['Long_Short'] = dfnewlong['Long_Short'].fillna('Long')
    dfnewlong.Symbol = dfnewlong.Symbol.str.strip()
    ticker = dfnewlong['Symbol']
    livequote = si.get_live_price(ticker)
    dfnewlong['Entry_Price'] = dfnewlong['Entry_Price'].fillna(livequote)
    df2 = pd.concat([df2, dfnewlong])
    print(df2.columns)

create_long()

I keep getting the error: "KeyError: "None of ['Symbol'] are in the columns"

What I'm trying to accomplish is for the function to pull the stock symbols into the variables, but it doesn't seem to work because the stock symbols are in the index column.

Links to the files being used by the code: https://drive.google.com/file/d/1prqdn9l7wnA5hg2gKqGeubeWLo5kRvI6/view?usp=sharing https://drive.google.com/file/d/1vkFZYBPJqWzjcYPJFKyRHIMLkg5zJ7Oy/view?usp=sharing

Any suggestions ?

Upvotes: 0

Views: 1080

Answers (1)

ExplodingGayFish
ExplodingGayFish

Reputation: 2897

You need to call reset_index first, since you already set Symbol as index:

print(dfnewlong.index)
dfnewlong.reset_index(inplace=True) # <----- here
#dfnewlong.set_index('Symbol', inplace=True, drop=False)

Also you can remove the next line (the set_index call) if you want to unset 'Symbol' as index columns

Upvotes: 1

Related Questions