亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將多列字典轉換為數據框?

如何將多列字典轉換為數據框?

尚方寶劍之說 2023-09-02 16:13:38
我正在使用 cryptocompare API 并嘗試提取一堆不同代碼的歷史數據。從 Excel 電子表格中讀取股票代碼,然后通過 API 加載以獲取每個股票代碼的歷史價格。這是我當前收到的數據框: https: //docs.google.com/spreadsheets/d/1jQ7F0H2D-voTBxjHI3QVPTRNyR4m4qKob8NE04JWVY0/edit ?usp=sharing我想知道一些事情:如何使索引成為日期和我如何訪問“關閉”數據點?這是目前我的代碼:import pandas as pdimport cryptocompareimport datetimedf = pd.read_excel('C:/Users/Jacob/Downloads/Crypto Tickers1.xlsx', sheet_name='Sheet1')tickers_list = df['Ticker'].tolist()data = pd.DataFrame(columns=tickers_list)for ticker in tickers_list:    data[ticker] = cryptocompare.get_historical_price_day(ticker, 'USD', limit = 1000 , exchange='CCCAGG', toTs=datetime.datetime(2020,9,22)) export_excel = data.to_excel(r'C:/Users/Jacob/Downloads/Crypto Scrape df.xlsx', sheet_name='Sheet1', index= True)
查看完整描述

1 回答

?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

  • 對于每個股票代碼,該文件由dicts, as組成的列。strings

  • 加載您的文件pandas.read_excel。

  • 使用 .將類型轉換str為類型。dictast.literal_eval

  • 將 的每一列轉換dicts為一個數據框pandas.json_normalize。

    • 每個數據幀將被添加到dictdf_dict,其中鍵將是股票代碼。

  • 將股票代碼作為一列添加到每個數據幀

  • 將所有數據幀組合成一個數據幀,并帶有pandas.concat.

  • 使用 , 將列轉換'time'為日期時間格式pandas.to_datetime,并設置為索引。

  • 使用或訪問該'close'列。df.closedf['close']

  • 用于pandas.DataFrame.pivot獲取'close'值,以代碼作為標題和'time'索引。

import pandas as pd

from ast import literal_eval


# load the file

df = pd.read_excel('Crypto Scrape df.xlsx', sheet_name='Sheet1')


# drop the Unnamed column

df.drop(columns=['Unnamed: 0'], inplace=True)


# apply literal_eval to all columns to convert them from strings to dicts

df = df.applymap(literal_eval)


# create a dict of dataframes in a dict comprehension

df_dict = {col: pd.json_normalize(df[col]) for col in df.columns}


# add a ticker column

for k, d in df_dict.items():

    df_dict[k]['ticker'] = k


# combine all the dicts into a single dataframe

df = pd.concat(df_dict.values()).reset_index(drop=True)


# convert the time column to a datetime format

df.time = pd.to_datetime(df.time, unit='s')


# set the time column as the index

df.set_index('time', inplace=True)


# to get only close values under each ticker with time as the index

dfp = df[['close', 'ticker']].pivot(columns='ticker', values='close')


# set the column and index name as None, if desired

dfp.columns.name = None

dfp.index.name = None

顯示前 5 行和前 5 列dfp

# display(dfp.iloc[:5, :5])


             ADA  ALGO  ATOM     BAT      BCH

2017-12-27  0.00   0.0   0.0  0.3200  2710.64

2017-12-28  0.00   0.0   0.0  0.6891  2484.96

2017-12-29  0.00   0.0   0.0  0.4013  2619.32

2017-12-30  0.59   0.0   0.0  0.4001  2209.96

2017-12-31  0.71   0.0   0.0  0.5910  2371.83


查看完整回答
反對 回復 2023-09-02
  • 1 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號