user308827
user308827

Reputation: 21961

Convert datetime index in pandas to separate columns

                   0         1          2         3         4         5
2015-01-01  2.847222 -5.197222 -13.900000  1.913889  0.872222  3.988889
2015-01-02  3.202778 -6.925000 -15.386111  0.911111  0.858611  4.352778

In the dataframe above, the leftmost column is the index and represents the datetime. How do I add 3 columns which represent the year, month and day separately? The outcome looks like:

            0    1  2   3         4          5         6         7         8
2015-01-01  2015 1  1   2.847222 -5.197222 -13.900000  1.913889  0.872222  3.988889
2015-01-02  2015 1  2   3.202778 -6.925000 -15.386111  0.911111  0.858611  4.352778

Upvotes: 1

Views: 1358

Answers (1)

Zero
Zero

Reputation: 76917

Here's one way to do it

Change the columns names

In [162]: df.columns = range(3, 9)

In [163]: df
Out[163]:
                   3         4          5         6         7         8
2015-01-01  2.847222 -5.197222 -13.900000  1.913889  0.872222  3.988889
2015-01-02  3.202778 -6.925000 -15.386111  0.911111  0.858611  4.352778

Then add, year, month, day to 0,1,2 columns

In [164]: df[0] = df.index.year

In [165]: df[1] = df.index.month

In [166]: df[2] = df.index.day

In [167]: df
Out[167]:
                   3         4          5         6         7         8     0  \
2015-01-01  2.847222 -5.197222 -13.900000  1.913889  0.872222  3.988889  2015
2015-01-02  3.202778 -6.925000 -15.386111  0.911111  0.858611  4.352778  2015

            1  2
2015-01-01  1  1
2015-01-02  1  2

Upvotes: 1

Related Questions