簡體   English   中英

如何在 function 中引用 pandas dataframe 的索引列

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

我不知道如何讓這段代碼正常運行。

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()

我不斷收到錯誤消息:“ KeyError: "None of ['Symbol'] are in the columns

我想要完成的是讓 function 將股票代碼拉入變量中,但它似乎不起作用,因為股票代碼在索引列中。

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 =分享

有什么建議么?

您需要先調用reset_index ,因為您已經將Symbol設置為索引:

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

如果您想取消將“符號”設置為索引列,也可以刪除下一行( set_index調用)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM