How can I merge columns Year
, Month
, and Day
into one column of months?
import pandas as pd
data = {'Subject': ['A', 'B', 'C', 'D'],
'Year':[1, 0, 0, 2],
'Month':[5,2,8,8],
'Day': [3,22,5,12]}
df = pd.DataFrame(data)
print(df)
My example gives the resulting dataframe:
Subject Year Month Day
0 A 1 5 3
1 B 0 2 22
2 C 0 8 5
3 D 2 8 12
I would like it to look like this:
*note: I rounded this so these numbers are not 100% accurate
Subject Months
0 A 17
1 B 3
2 C 8
3 D 32
CodePudding user response:
Assuming the Gregorian calendar:
- 365.2425 days/year
- 30.436875 days/month.
day_year = 365.2425
day_month = 30.436875
df['Days'] = df.Year.mul(day_year) df.Month.mul(day_month) df.Day
# You could also skip this step and just do:
# df['Months'] = (df.Year.mul(day_year) df.Month.mul(day_month) df.Day).div(day_month)
df['Months'] = df.Days.div(day_month)
print(df.round(2))
Output:
Subject Year Month Day Days Months
0 A 1 5 3 520.43 17.10
1 B 0 2 22 82.87 2.72
2 C 0 8 5 248.50 8.16
3 D 2 8 12 985.98 32.39