I am having a dataframe like this
Date Temerature
2016-01-01 3
2017-01-01 4
2016-02-01 5
2017-02-01 7
2016-03-01 2
2017-03-01 4
Now, I want to get the Average temperature temperature based on Month and day like this
Date Temperature
Jan 1 3.5
Feb 1 6
Mar 1 3
So, I want to make a new data frame like this, How is it possible in python?
CodePudding user response:
Try:
df['Date'] = pd.to_datetime(df['Date'])
df.groupby(df['Date'].dt.strftime('%B %d'), sort=False).mean()
Output:
Temerature
Date
January 01 3.5
February 01 6.0
March 01 3.0
CodePudding user response:
Try this:
import pandas as pd
df = pd.DataFrame({'Date': ['2016-01-01', '2017-01-01', '2016-02-01', '2017-02-01', '2016-03-01', '2017-03-01'],
'Temerature': [3, 4, 5, 7, 2, 4]})
df['Date'] = pd.to_datetime(df['Date'])
df['Month'] = df['Date'].dt.month
df['Day'] = df['Date'].dt.day
df.groupby(['Month', 'Day'])['Temerature'].mean().reset_index()
CodePudding user response:
Your table:
import pandas as pd
df = pd.DataFrame({
"Date":["2016-01-01","2017-01-01","2016-02-01","2017-02-01","2016-03-01 ","2017-03-01 "],
"Temerature":[3,4,5,7,2,4]
})
Transform data:
df["Date"] = pd.to_datetime(df["Date"], infer_datetime_format=True)
df["Date"] = df["Date"].dt.strftime('%B %d')
df = df.groupby(["Date"], sort=False).mean().reset_index()
Output:
print(df)
Date Temerature
0 January 01 3.5
1 February 01 6.0
2 March 01 3.0