熊猫-增量(年,月)多索引列和年和月列

时间:2018-12-21 23:12:08

标签: python-3.x pandas datetime dataframe multi-index

使用数据框df,例如:

           YEAR     MONTH     VALUE
(2017,1) 2017        1          1
(2017,2) 2017        2          1
(2017,3) 2017        3          1

如何自动在数据帧上生成新的增量行,例如:

       YEAR     MONTH     VALUE
(2017,1) 2017        1          1
(2017,2) 2017        2          1
(2017,3) 2017        3          1
(2017,4) 2017        4          1
(2017,5) 2017        5          1
(2017,6) 2017        6          1

我看到可以通过创建一个熊猫系列并将其附加到df上来添加新行,但是我有很多行要添加,这种方法似乎是超级手动的。

我已使用{p>将MONTHYEAR设置为datetime

df["MONTH"]=pd.to_datetime(df["MONTH"], format='%m')
df["YEAR"]=pd.to_datetime(df["YEAR"], format='%Y')

但是我不确定如何自动将新行增加到现有数据框上。

1 个答案:

答案 0 :(得分:1)

您可以尝试

import dateutil.relativedelta

last_row = df.iloc[-1]
last_value = last_row['VALUE'] # or change it
last_date = datetime.datetime(last_row['YEAR'], last_row['MONTH'], 1)


t = [last_date + dateutil.relativedelta.relativedelta(months = k + 1) for k in range(12)]
df1 = [{'YEAR' : k.year, 'MONTH' : k.month, 'VALUE' : last_value} for k in t]
df1 = pandas.DataFrame(df1, index = [(k.year, k.month) for k in t])

dfnew = df.append(df1)

print(dfnew)


            MONTH  VALUE  YEAR
(2017, 1)       1      1  2017
(2017, 2)       2      1  2017
(2017, 3)       3      1  2017
(2017, 4)       4      1  2017
(2017, 5)       5      1  2017
(2017, 6)       6      1  2017
(2017, 7)       7      1  2017
(2017, 8)       8      1  2017
(2017, 9)       9      1  2017
(2017, 10)     10      1  2017
(2017, 11)     11      1  2017
(2017, 12)     12      1  2017
(2018, 1)       1      1  2018
(2018, 2)       2      1  2018
(2018, 3)       3      1  2018

​