【发布时间】: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