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

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

根據 pandas 中的時間序列創建月 x 年的數據框

根據 pandas 中的時間序列創建月 x 年的數據框

慕田峪9158850 2023-02-07 16:29:15
我有一個時間序列數據,其中包含幾年來每個月的天數,并嘗試創建一個新的數據框,該數據框將以月為行,以年為列。我有這個    DateTime    Days    Month   Year            2004-11-30  3   November    2004    2004-12-31  16  December    2004    2005-01-31  12  January     2005    2005-02-28  11  February    2005    2005-03-31  11  March       2005    ... ... ... ...    2019-06-30  0   June        2019    2019-07-31  2   July        2019    2019-08-31  5   August      2019    2019-09-30  5   September   2019    2019-10-31  3   October     2019我正在努力得到這個Month     2004  2005 ... 2019January   nan   12       7February  nan   11       9...November  17    17       nanDecember  14    15       nan我創建了一個新的數據框,第一列表示月份,并嘗試遍歷第一個數據框以將新列(年)和信息添加到單元格,但檢查第一個數據框(天)中的月份是否與月份匹配的條件新數據幀中的(輸出)永遠不會為真,因此新數據幀永遠不會更新。我想這是因為以天為單位的月份與同一迭代中輸出的月份永遠不同。for index, row in days.iterrows():print(days.loc[index, 'Days'])    #this prints out as expectedfor month in output.items():    print(index.month_name())     #this prints out as expected    if index.month_name()==month:        output.at[month, index.year]=days.loc[index, 'Days']    #I wanted to use this to fill up the cells, is this right?        print(days.loc[index, 'Days'])      #this never gets printed out你能告訴我如何解決這個問題嗎?或者也許有更好的方法來完成結果而不是迭代?這是我第一次嘗試在 python 中使用庫,因此我將不勝感激。
查看完整描述

1 回答

?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

使用pivot, 如果您的輸入數據框每月和每年只有一個值:


df.pivot('Month', 'Year', 'Days')

輸出:


Year      2004 2005 2019

Month                   

August     NaN  NaN    5

December    16  NaN  NaN

February   NaN   11  NaN

January    NaN   12  NaN

July       NaN  NaN    2

June       NaN  NaN    0

March      NaN   11  NaN

November     3  NaN  NaN

October    NaN  NaN    3

September  NaN  NaN    5


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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