如何在函数中引用数据帧的索引列

2024-10-02 04:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何让这段代码正常运行

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

我试图实现的是函数将股票符号拉入变量,但它似乎不起作用,因为股票符号在索引列中

代码正在使用的文件的链接: https://drive.google.com/file/d/1prqdn9l7wnA5hg2gKqGeubeWLo5kRvI6/view?usp=sharinghttps://drive.google.com/file/d/1vkFZYBPJqWzjcYPJFKyRHIMLkg5zJ7Oy/view?usp=sharing

有什么建议吗


Tags: csv代码readindexbuycolsymbolloc
1条回答
网友
1楼 · 发布于 2024-10-02 04:25:14

您需要首先调用reset_index,因为您已经将Symbol设置为索引:

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

此外,如果要取消将“Symbol”设置为索引列,还可以删除下一行(调用set_index

相关问题 更多 >

    热门问题