Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put Month and Year in the same Column in Python Pandas

Column1   Month    Quantity Year
48         4         12.00  2006
49         5         13.00  2006
50         6         46.00  2006
51         7         11.00  2006
52         8         18.00  2006
53         9         16.00  2006
54        10         28.00  2006
83         1          6.00  2006

How can I merge the month column with the year column, and get meaningful time data?

like image 729
DMang Avatar asked Apr 04 '17 18:04

DMang


People also ask

How do you get year and month pandas?

Suppose we want to access only the month, day, or year from date, we generally use pandas. Method 1: Use DatetimeIndex. month attribute to find the month and use DatetimeIndex. year attribute to find the year present in the Date.


2 Answers

In [42]: df['Date'] = pd.to_datetime(df.assign(Day=1).loc[:, ['Year','Month','Day']])

In [43]: df
Out[43]:
   Column1  Month  Quantity  Year       Date
0       48      4      12.0  2006 2006-04-01
1       49      5      13.0  2006 2006-05-01
2       50      6      46.0  2006 2006-06-01
3       51      7      11.0  2006 2006-07-01
4       52      8      18.0  2006 2006-08-01
5       53      9      16.0  2006 2006-09-01
6       54     10      28.0  2006 2006-10-01
7       83      1       6.0  2006 2006-01-01

Or much nicer solution from @piRSquared:

In [55]: df['Date'] = pd.to_datetime(df[['Year', 'Month']].assign(Day=1))

In [56]: df
Out[56]:
   Column1  Month  Quantity  Year       Date
0       48      4      12.0  2006 2006-04-01
1       49      5      13.0  2006 2006-05-01
2       50      6      46.0  2006 2006-06-01
3       51      7      11.0  2006 2006-07-01
4       52      8      18.0  2006 2006-08-01
5       53      9      16.0  2006 2006-09-01
6       54     10      28.0  2006 2006-10-01
7       83      1       6.0  2006 2006-01-01
like image 88
MaxU - stop WAR against UA Avatar answered Oct 20 '22 08:10

MaxU - stop WAR against UA


df['Date'] = pd.to_datetime(df.Year.astype(str) + '-' + df.Month.astype(str))
print(df)

    Column1  Month  Quantity  Year       Date
0       48      4      12.0  2006 2006-04-01
1       49      5      13.0  2006 2006-05-01
2       50      6      46.0  2006 2006-06-01
3       51      7      11.0  2006 2006-07-01
4       52      8      18.0  2006 2006-08-01
5       53      9      16.0  2006 2006-09-01
6       54     10      28.0  2006 2006-10-01
7       83      1       6.0  2006 2006-01-01

like image 29
piRSquared Avatar answered Oct 20 '22 08:10

piRSquared