【问题标题】:Creating a dataframe with months x years based on time series in pandas根据 Pandas 中的时间序列创建月 x 年的数据框
【发布时间】:2020-10-19 18:28:00
【问题描述】:

我有一个时间序列数据,其中包含数年来每个月的天数,并尝试创建一个新的数据框,该数据框将月作为行,将年作为列。

我有这个

    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 ... 2019

January   nan   12       7
February  nan   11       9
...
November  17    17       nan
December  14    15       nan

我创建了一个新的数据框,第一列表示月份,并尝试遍历第一个数据框以将新列(年)和信息添加到单元格中,但条件是检查第一个数据框中的月份是否(天)匹配新数据框(输出)中的月份永远不会为真,因此新数据框永远不会更新。我猜这是因为天数中的月份与同一迭代中输出的月份不同。

for index, row in days.iterrows():
print(days.loc[index, 'Days'])    #this prints out as expected
for 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 中使用库,所以我希望能得到一些帮助。

【问题讨论】:

    标签: python pandas dataframe time-series


    【解决方案1】:

    如果您的输入数据框每个月和年只有一个值,请使用 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
    

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 2021-01-07
      • 1970-01-01
      相关资源
      最近更新 更多