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

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

在 Python 中按共同日期加入時間序列(數據框和系列/列表問題)

在 Python 中按共同日期加入時間序列(數據框和系列/列表問題)

白衣染霜花 2022-10-06 15:50:53
菜鳥在這里。請原諒我仍在學習的格式。我正在嘗試創建一個包含三列的時間序列(我認為是數據框?)。一個是日期列,下一個是庫存列,最后一個是價格列。我已經提取了兩個單獨的系列(日期和庫存;日期和價格),我想合并這兩個系列,這樣我就可以看到三列而不是兩組兩列。這是我的代碼。import jsonimport numpy as npimport pandas as pdfrom urllib.error import URLError, HTTPErrorfrom urllib.request import urlopenclass EIAgov(object):    def __init__(self, token, series):        '''        Purpose:        Initialise the EIAgov class by requesting:        - EIA token        - id code(s) of the series to be downloaded        Parameters:        - token: string        - series: string or list of strings        '''        self.token = token        self.series = series    def __repr__(self):        return str(self.series)    def Raw(self, ser):        # Construct url        url = 'http://api.eia.gov/series/?api_key=' + self.token + '&series_id=' + ser.upper()        try:            # URL request, URL opener, read content            response = urlopen(url);            raw_byte = response.read()            raw_string = str(raw_byte, 'utf-8-sig')            jso = json.loads(raw_string)            return jso        except HTTPError as e:            print('HTTP error type.')            print('Error code: ', e.code)        except URLError as e:            print('URL type error.')            print('Reason: ', e.reason)  請注意,“mytoken”需要替換為 eia.gov API 密鑰。我可以讓它成功地創建兩個列表的輸出......但是為了合并列表,我試圖在最后添加這個:joined_frame = pd.concat([ngstor, ngpx], axis = 1, sort=False)print(joined_frame.GetData())但我得到一個錯誤 ("TypeError: cannot concatenate object of type '<class 'list'>'; only Series and DataFrame objs are valid")因為顯然我不知道列表和系列之間的區別。如何按日期列合并這些列表?非常感謝您的幫助。(也請隨意告訴我為什么我在這篇文章中正確格式化代碼很糟糕。)
查看完整描述

1 回答

?
慕標5832272

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

如果您想在其余代碼中將它們作為 DataFrame 進行操作,您可以將它們轉換ngstor為ngpxDataFrame,如下所示:


import pandas as pd

# I create two lists that look like yours

ngstor = [[1,2], ["2020-04-03", "2020-05-07"]]

ngpx = [[3,4] , ["2020-04-03", "2020-05-07"]]

# I transform them to DataFrames

ngstor = pd.DataFrame({"value1": ngstor[0],

                       "date_col": ngstor[1]})

ngpx = pd.DataFrame({"value2": ngpx[0],

                       "date_col": ngpx[1]})


然后您可以使用pandas.merge或pandas.concat:


# merge option

joined_framed = pd.merge(ngstor, ngpx, on="date_col",

                          how="outer")

# concat option

ngstor = ngstor.set_index("date_col")

ngpx = ngpx.set_index("date_col")

joined_framed = pd.concat([ngstor, ngpx], axis=1,

                          join="outer").reset_index()


結果將是:


    date_col  value1  value2

0  2020-04-03       1       3

1  2020-05-07       2       4


查看完整回答
反對 回復 2022-10-06
  • 1 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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