I have attached the code in the form of a screenshot here. Any help to get this to process through my flow would be appreciated!
@Joseph Crapanzano
Hi, I have modified your python script:
import pandas as pd
⌗import tabpy
⌗from tableau_tools import prep_decimal, prep_int, prep_bool, prep_string, prep_date, prep_datetime
# Define duration_columns as a global variable
duration_columns = [
'Step 1',
'Step 2',
'Step 3',
'Step 4',
'Step 5',
'Step 6',
'Step 7',
]
def moving_average(data, window=10, max_visits=150):
# Filter rows based on Appointment Status
filtered_data = data[(data['appt_status'] == 'CHECKED_OUT') | (data['appt_status'] == 'CHECKING_OUT')]
# Group by Appointment Type ID and sort by Appointment DateTime of Service
grouped_data = filtered_data.groupby('type_id')
# Initialize moving average columns with NaN
for duration_column in duration_columns:
data[f"Moving Average {duration_column}"] = float('nan')
for name, group in grouped_data:
sorted_group = group.sort_values(by='datetime')
sorted_group = sorted_group.head(max_visits)
if len(sorted_group) >= window:
for duration_column in duration_columns:
if duration_column in sorted_group.columns:
sorted_group[f"Moving Average {duration_column}"] = sorted_group[duration_column].rolling(window=window).mean()
# Update the moving average columns in the original dataset
data.loc[sorted_group.index, [f"Moving Average {duration_column}" for duration_column in duration_columns]] = sorted_group[[f"Moving Average {duration_column}" for duration_column in duration_columns]]
return data
def get_output_schema():
return pd.DataFrame({
**{f'Moving Average {name}': prep_decimal() for i, name in enumerate(['Step 1', 'Step 2', 'Step 3', 'Step 4', 'Step 5', 'Step 6', 'Step 7'], start=1)},
})
def prep_script(input):
# Convert input data to pandas DataFrame
input_data = input
# Call the moving_average function
output = moving_average(input_data)
print(output)
# Convert the result back to a list of dicts
#output = [row.to_dict() for _, row in result.iterrows()]
# Get the output schema using the get_output_schema function
#output_schema = get_output_schema()
# Return output and schema
return output#, output_schema
Now it is working, I think you can start from here.
If this post resolves the question, would you be so kind to "Select as Best"?. This will help other users find the same answer/resolution and help community keep track of answered questions. Thank you.
Regards,
Diego Martinez
Tableau Visionary and Forums Ambassador