簡體   English   中英

根據唯一值創建 pandas DataFrame 的新列?

[英]Creating new columns of pandas DataFrame based on unique values?

我在 pandas 中有一個 DataFrame,它有一個日期、一個股票代碼(即“MSFT”),以及該股票在該特定日期的開盤價和收盤價以及其他數據點。 因此,我的數據集中每個股票代碼基本上都有一個日期副本。

我想轉換我的 DataFrame:


    Open    High    Low Close   Adj Close   Volume  Name
Date                            
2006-12-04  0.06508 0.06508 0.06508 0.06508 -0.098360   193352.0    AAIT
2006-12-05  0.06464 0.06464 0.06464 0.06464 -0.097695   81542.0 AAIT
2006-12-06  0.06596 0.06596 0.06552 0.06596 -0.099690   158115.0    AAIT
2006-12-07  0.06596 0.06596 0.06596 0.06596 -0.099690   65731.0 AAIT
2006-12-11  0.06596 0.06596 0.06596 0.06596 -0.099690   542561.0    AAIT

變成類似的東西:


    ADBE_Adj Close  ADBE_Close  ADBE_High   ADBE_Low    ADBE_Open   ADBE_Volume ADXS_Adj Close  ADXS_Close  ADXS_High   ADXS_Low    ... 
2019-12-19  327.630005  327.630005  327.959991  324.26001   324.380005  2561400.0   0.581   0.581   0.59    0.550   ...
2020-11-17  467.950012  467.950012  469.910004  460.00000   461.660004  2407600.0   0.393   0.393   0.40    0.383   ...

我正在使用我編寫的代碼手動執行此操作:

df = pd.DataFrame() # init empty dataframe
dates_set = set(stocks_df.index)
print('Going through {} days of data.'.format(len(dates_set)))
for _date in tqdm(dates_set):
    row = {}
    for symbol in filtered_stock_list:
        stock_at_date = stocks_df.loc[(stocks_df['Name']==symbol) &
                                     (stocks_df.index==_date)]
        for attribute in ['Open','High','Low','Close','Adj Close','Volume']:
            try:
                row[symbol + '_' + attribute] = float(stock_at_date[attribute])
            except Exception as e:
                row[symbol + '_' + attribute] = None
    #print(row)
    ser = pd.Series(data=row, name=_date)
    df = df.append(ser)

但不幸的是,這段代碼非常未經優化,需要幾個小時才能運行。 我一直在研究各種不同的 pandas 操作,但我不知道該怎么做。

利用:

new_df = (df.set_index('Name', append=True)
            .loc[:, ['Open','High','Low','Close','Adj Close','Volume']]
            .unstack('Name'))
new_df.columns = [f'{x}_{y}' for x, y in new_df.columns]

暫無
暫無

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

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