df['DeliveryDate'] = pd.todatetime(df['DeliveryDate']) today = datetime.now() startdate…
- User
df['DeliveryDate'] = pd.to_datetime(df['DeliveryDate']) today = datetime.now() start_date = datetime(today.year + int(today.month/12), (today.month%12) + 1, 1) end_date = datetime(today.year + int((today.month + 3)/12), ((today.month+3)%12) + 1, 1)
df_months = df[(df['DeliveryDate'] >= start_date) & (df['DeliveryDate'] < end_date)] print(df_months)
I have the above dataframe in Pandas.
I want to create the following dataframe: The rows will be months (first month, second,. up to fourth month) and columns will be countries (Slovenia, Hungary and Germany) - those countries are also the only ones in the dataframe. I want to calculate the average prices. So for e.g. the first entry would be the average price from the first month in Slovenia, ...
- Assistant
To create the desired dataframe, you can use the
pivot_tablefunction in pandas.First, make sure you have imported the necessary libraries:
import pandas as pd from datetime import datetimeThen, adjust the code accordingly:
# Convert 'DeliveryDate' column to datetime df['DeliveryDate'] = pd.to_datetime(df['DeliveryDate']) # Get current date and define start and end dates for the selected 3-month period today = datetime.now() start_date = datetime(today.year + int(today.month/12), (today.month%12) + 1, 1) end_date = datetime(today.year + int((today.month + 3)/12), ((today.month+3)%12) + 1, 1) # Filter the dataframe for the selected 3-month period df_months = df[(df['DeliveryDate'] >= start_date) & (df['DeliveryDate'] < end_date)] # Create a pivot table to calculate average prices by month and country df_avg_prices = pd.pivot_table(df_months, values='Price', index=df_months['DeliveryDate'].dt.month, columns='Country', aggfunc='mean') # Rename the index and columns df_avg_prices.index.name = 'Month' df_avg_prices.columns.name = 'Country' print(df_avg_prices)The resulting
df_avg_pricesdataframe will have months as rows and countries as columns, containing the average prices for each combination.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.