我是 Python 和 Pandas 的新手。我有一個 Pandas 數據框,由許多股票(例如 S&P 500)的多年時間序列數據組成。我想逐個迭代每個唯一的股票代碼并計算收盤價的技術指標。我一直在嘗試從主數據框中為每只獨特的股票創建一個新的數據框及其所有價格歷史,然后將其傳遞給一個方法,該方法將進行技術分析而不是傳遞主數據框。這是我的數據框中的一些示例數據:Id Symbol Date Open High Low Close Volume1 A99 2012-01-02 730.019 730.019 730.019 730.019 02 ABA 2012-01-02 4.200 4.200 4.200 4.200 03 AFI 2012-01-02 5.360 5.360 5.360 5.360 04 AIA 2012-01-02 2.520 2.520 2.520 2.520 0...501 A99 2012-01-03 730.019 730.019 730.019 730.019 0...我嘗試過 loc、iloc 和 groupby 等索引器,但沒有運氣。我已經閱讀了很多文章,例如 根據 Pandas 中列中的值從 DataFrame 中選擇行, 但沒有一篇完全符合我的要求。所有這些的主要問題是你必須有一個文字搜索條件,而我想要一個變量過濾器名稱,即股票名稱。我的數據表示例如下:這是我當前不起作用的代碼片段:# 從數據庫中獲取數據 df = stockPrices.get_data()# Create technical indicators for each distinct stock# First get a series of all unique stock codests = pd.Series(df.Symbol.unique())# Iterate through the series and call the technical indicator methodfor row in ts: # filter for just this stock filtered_df = df.loc[df['Symbol'] == row] df = stockPrices.calc_technicals(filtered_df, row)任何指針將不勝感激。
2 回答

ibeautiful
TA貢獻1993條經驗 獲得超6個贊
選擇所有匹配符號的行作為“A99”
filtered_df = df.loc[df['Symbol'] == 'A99']
也可以嘗試:
filtered_df = df.loc[df['Symbol'].isin('A99')]

波斯汪
TA貢獻1811條經驗 獲得超4個贊
你的代碼沒有錯。group_by不適合這里,因為沒有組操作。請檢查您的方法stockPrices.calc_technicals。
df=pd.DataFrame({'symbol':['a','a','a','b','b'],'v':[1,2,3,4,5]})
ts=pd.Series(df.symbol.unique())
for i in ts:
filtered_df=df.loc[df.symbol==i]
print(filtered_df)
symbol v
0 a 1
1 a 2
2 a 3
symbol v
3 b 4
4 b 5
添加回答
舉報
0/150
提交
取消