look at my ensemble code again, from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, AutoETS, DynamicOptimizedTheta
from statsforecast.utils import ConformalIntervals
import numpy as np
import polars as pl
Print the average group accuracy and group bias over all folds for the ensemble model
print('Average Group Accuracy: ', round(group_accuracy, 4))
print(‘Average Group Bias: ‘, round(group_bias, 4))
Fit the models on the entire dataset
Assistant
Yes, you can split the unique_id back into its four original components ('MaterialID', 'SalesOrg', 'DistrChan', 'CL4') and rename the column 'ds' to 'WeekDate'. In Python, you would do the following with your forecasts_df DataFrame.
Here's an example of code that you might use to accomplish this:
# Assume forecasts_df is your result DataFrame
forecasts_df = forecasts_df.with_columns([
forecasts_df['unique_id'].str.split('_').alias("split_id")
])
# Expand the "split_id" list into its own separate columns
forecasts_df = forecasts_df.with_columns([
forecasts_df['split_id'].arr.get(0).alias('MaterialID'),
forecasts_df['split_id'].arr.get(1).alias('SalesOrg'),
forecasts_df['split_id'].arr.get(2).alias('DistrChan'),
forecasts_df['split_id'].arr.get(3).alias('CL4')
])
# Drop the 'unique_id' and 'split_id' columns
forecasts_df = forecasts_df.drop(['unique_id', 'split_id'])
# Rename 'ds' to 'WeekDate'
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Now forecasts_list will use the updated dataframe
forecasts_list = []
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
for forecast in forecasts_list:
print(forecast)
User
where do I put this code
Assistant
You can put this code after you've finalized your forecasts and are ready to transform the id back to its original form. By following your initial code structure, these lines should be placed at the end, after you've created forecasts_df with all the required columns.
Let's integrate the code snippet within your existing code, so you know exactly where to put it.
# Suppose your code ends at this point after adding the ensemble forecast
# and its prediction intervals as new columns to the DataFrame
forecasts_df = forecasts_df.with_columns([ensemble_forecast_series, ensemble_lo_95_series, ensemble_hi_95_series])
# At this point, add the following code to process the 'unique_id' and 'ds' transformations:
# Split the 'unique_id' back into its four original components
forecasts_df = forecasts_df.with_columns([
forecasts_df['unique_id'].str.split('_').alias("split_id")
]).with_columns([
pl.col('split_id').arr.get(0).alias('MaterialID'),
pl.col('split_id').arr.get(1).alias('SalesOrg'),
pl.col('split_id').arr.get(2).alias('DistrChan'),
pl.col('split_id').arr.get(3).alias('CL4')
])
# Drop the 'unique_id' and 'split_id' columns
forecasts_df = forecasts_df.drop(['unique_id', 'split_id'])
# Rename 'ds' to 'WeekDate'
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Now you can create the forecasts_list and print it as you've done before
forecasts_list = []
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
# Printing the forecasts in the original structure
for forecast in forecasts_list:
print(forecast)
User
but what baout this block # Reorder the columns
forecasts_df = forecasts_df.select([
"unique_id",
"ds",
"EnsembleForecast",
"Ensemble-lo-95",
"Ensemble-hi-95",
"ADIDA",
"ADIDA-lo-95",
"ADIDA-hi-95",
"CrostonClassic",
"CrostonClassic-lo-95",
"CrostonClassic-hi-95",
"IMAPA",
"IMAPA-lo-95",
"IMAPA-hi-95",
"TSB",
"TSB-lo-95",
"TSB-hi-95"
])
Assistant
Given the new block of code that reorders the columns, we want to make sure that the reversal of the unique_id and the renaming of ds to WeekDate are done before this reordering. After these operations, you won't have a unique_id anymore, but four separate columns: MaterialID, SalesOrg, DistrChan, and CL4. And ds will be renamed to . So, the reordering should also be updated to reflect these changes.
User
Assistant
User
Assistant
Your updated code appears to be correct based on what you've shown. You've successfully incorporated the steps to revert the unique_id back into its constituent parts: MaterialID, SalesOrg, DistrChan, and CL4. You've also renamed the ds column back to WeekDate. Then, you've reordered the columns to match your new structure.
Keep in mind that when you are working with real data, it is always a good practice to include sanity checks throughout your script to make sure data transformations go as expected. For example, you might want to print out a few rows of your dataframe at different stages of its transformation to verify that columns are added, renamed, and reordered accurately.
Assuming that the rest of your code is functioning correctly, the final list forecasts_list, when printed, should show data with the columns MaterialID, SalesOrg, DistrChan, CL4, and instead of and , along with each forecast and its prediction intervals.
User
error --------------------------------------------------------------------------
SchemaError Traceback (most recent call last)
Cell In[14], line 119
113 # Split the unique_id concat into the original columns
114 forecasts_df = forecasts_df.with_columns([
115 forecasts_df['unique_id'].str.split('_').alias('split_id')
116 ])
118 forecasts_df = forecasts_df.with_columns([
--> 119 forecasts_df['split_id'].arr.get(0).alias('MaterialID'),
120 forecasts_df['split_id'].arr.get(1).alias('SalesOrg'),
121 forecasts_df['split_id'].arr.get(2).alias('DistrChan'),
122 forecasts_df['split_id'].arr.get(3).alias('CL4')
123 ])
125 # Drop the ‘unique_id’ and ‘split_id’ columns
126 forecasts_df = forecasts_df.drop(['unique_id', 'split_id'])
Assistant
The error you encountered is because of the mismatch between the expected data type and what was provided. In this case, the split_id is likely a list of strings, but Pandas is expecting a fixed-size list representation. This issue might have arisen due to incompatibilities or issues in serialization from Polars to Pandas, or vice versa.
In Polars, we should treat list operations properly to avoid issues. Let's try to correct your with_columns block and ensure correct list handling.
Here's the corrected part of your code:
# Once you split 'unique_id' into a list, you can directly extract each component using aliasing
# This replaces the original "split the unique_id" and "expand to columns" code sections
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('_').arr.get(0).alias('MaterialID'),
pl.col('unique_id').str.split('_').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('_').arr.get(2).alias('DistrChan'),
pl.col('unique_id').str.split('_').arr.get(3).alias('CL4')
]).drop('unique_id')
# Rename 'ds' to 'WeekDate'
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Now proceed as before to reorder the columns and generate your forecasts_list
# ...
User
Assistant
Your code looks mostly correct, however, there are a couple of typos and inconsistencies to address:
When splitting unique_id, you must specify the correct delimiter (underscore '_'), but in your code snippet, you're using an empty string ''. It should be '_' instead.
In renaming the split columns, one of your aliases 'MaterialI' seems to be a typo, it should likely be 'MaterialID'.
User
this is what I have now # Round the ensemble forecast and prediction intervals and convert to integer
forecasts_df = forecasts_df.with_columns([
pl.col("EnsembleForecast").round().cast(pl.Int32),
pl.col("Ensemble-lo-95").round().cast(pl.Int32),
pl.col("Ensemble-hi-95").round().cast(pl.Int32)
])
Split the unique_id concat into the original columns
You are still using an incorrect delimiter in the str.split('') function. It should be '_' and not ''. Additionally, make sure you drop any unnecessary intermediate columns and use the correct data type casting if needed.
Here's your corrected snippet:
# Round the ensemble forecast and prediction intervals and convert to integer
forecasts_df = forecasts_df.with_columns([
pl.col("EnsembleForecast").round().cast(pl.Int32),
pl.col("Ensemble-lo-95").round().cast(pl.Int32),
pl.col("Ensemble-hi-95").round().cast(pl.Int32)
])
# Split the unique_id concat into the original columns
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('_').arr.get(0).alias('MaterialID'),
pl.col('unique_id').str.split('_').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('_').arr.get(2).alias('DistrChan'),
pl.col('unique_id').str.split('_').arr.get(3).alias('CL4')
]).drop('unique_id')
# Rename ‘ds’ to ‘WeekDate’
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Reorder the columns
# Make sure to include all columns you want in your final DataFrame in the order you want them.
forecasts_df = forecasts_df.select([
"MaterialID",
"SalesOrg",
"DistrChan",
"CL4",
"WeekDate",
"EnsembleForecast",
"Ensemble-lo-95",
"Ensemble-hi-95",
# Include the rest of the columns you want in your final DataFrame
])
User
how about now # Split the unique_id concat into the original columns
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('').arr.get(0).alias('MaterialID'),
pl.col('unique_id').str.split('').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('').arr.get(2).alias('DistrChan'),
pl.col('unique_id').str.split('').arr.get(3).alias('CL4')
]).drop('unique_id')
Yes, that part of the code is correct now. You are splitting the unique_id into the original columns, dropping the unique_id after splitting, and renaming ds to WeekDate.
After the column reordering, just make sure to include all columns of interest in the select method to finalize your DataFrame. The snippet you've shown is correct in terms of syntax. However, the method seems incomplete as it ends abruptly and does not include all columns.
User
still have error
Assistant
User
this is the error --------------------------------------------------------------------------
SchemaError Traceback (most recent call last)
Cell In[16], line 114
107 forecasts_df = forecasts_df.with_columns([
108 pl.col("EnsembleForecast").round().cast(pl.Int32),
109 pl.col("Ensemble-lo-95").round().cast(pl.Int32),
110 pl.col("Ensemble-hi-95").round().cast(pl.Int32)
111 ])
113 # Split the unique_id concat into the original columns
--> 114 forecasts_df = forecasts_df.with_columns([
115 pl.col('unique_id').str.split('').arr.get(0).alias('MaterialID'),
116 pl.col('unique_id').str.split('').arr.get(1).alias('SalesOrg'),
117 pl.col('unique_id').str.split('').arr.get(2).alias('DistrChan'),
118 pl.col('unique_id').str.split('').arr.get(3).alias('CL4')
119 ]).drop('unique_id')
121 # Rename ‘ds’ to ‘WeekDate’
122 forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
Assistant
Based on the error message—it seems Polars expects a FixedSizeList instead of a list[str]. This discrepancy could be due to a mismatch between the data returned by splitting the unique_id field and how Polars expects list-structured data to be accessed/manipulated.
Let's try a different approach to see if it resolves the SchemaError:
Make sure the splitting operation is done only once and the results are stored in separate columns.
Extract the parts using a single expression before casting, which should avoid creating an intermediate list that might be causing the error.
The information you've provided suggests that unique_id is a str and the original columns MaterialID and DistrChan are i64 (integers), while SalesOrg and CL4 are str. This is important for ensuring the split and data castings are performed correctly.
User
also this is an example unique id concat 12529080_US01_10_5339183
Assistant
Thank you for providing an example of the unique_id after concatenation. Given the structure 12529080_US01_10_5339183, we can split the unique_id by underscores and cast numeric components back to integers where necessary.
Here's revised code to handle the unique ID:
import polars as pl
# Split the unique_id back into its original components and drop the original unique_id column
forecasts_df = forecasts_df.with_columns([
pl.col("unique_id").str.split("_").arr.get(0).cast(pl.Int64).alias("MaterialID"),
pl.col("unique_id").str.split("_").arr.get(1).alias("SalesOrg"),
pl.col("unique_id").str.split("_").arr.get(2).cast(pl.Int64).alias("DistrChan"),
pl.col("unique_id").str.split("_").arr.get(3).alias("CL4")
]).drop("unique_id")
# Rename 'ds' to 'WeekDate'
forecasts_df = forecasts_df.rename({"ds": "WeekDate"})
# Ensure that you continue the rest of the code pipeline as planned.
User
ColumnNotFoundError Traceback (most recent call last)
Cell In[15], line 114
107 forecasts_df = forecasts_df.with_columns([
108 pl.col("EnsembleForecast").round().cast(pl.Int32),
109 pl.col("Ensemble-lo-95").round().cast(pl.Int32),
110 pl.col("Ensemble-hi-95").round().cast(pl.Int32)
111 ])
113 # Split the unique_id concat into the original columns
--> 114 forecasts_df = forecasts_df.with_columns([
115 pl.col('unique_id”').str.split('').arr.get(0).cast(pl.Int64).alias('MaterialID'),
116 pl.col('unique_id').str.split('').arr.get(1).alias('SalesOrg'),
117 pl.col('unique_id').str.split('').arr.get(2).cast(pl.Int64).alias('DistrChan'),
118 pl.col('unique_id').str.split('').arr.get(3).alias('CL4')
119 ]).drop('unique_id')
121 # Rename ‘ds’ to ‘WeekDate’
122 forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
Assistant
The error you're encountering, ColumnNotFoundError: unique_id”, indicates that when attempting to access a column named unique_id” (with a closing quote character) in the DataFrame, Polars can't find it because of the typographical error. The name of your column in the DataFrame is likely unique_id without the additional quote.
Let's correct the syntax by removing the stray quote character and ensure the column name matches exactly as it appears in the DataFrame:
# Split the unique_id concat into the original columns
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('_').arr.get(0).cast(pl.Int64).alias('MaterialID'),
pl.col('unique_id').str.split('_').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('_').arr.get(2).cast(pl.Int64).alias('DistrChan'),
pl.col('unique_id').str.split('_').arr.get(3).alias('CL4')
]).drop('unique_id') # Removing the extra quote at the end of 'unique_id'
# Rename ‘ds’ to ‘WeekDate’
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
In this corrected version, we make sure to call the column without any additional punctuation or quotes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
Print the list
for forecast in forecasts_list:
print(forecast) you could see taht unique id was created using 4 columns concat # Concatenate ‘MaterialID’, ‘SalesOrg’, ‘DistrChan’, ‘CL4’ to a new column ‘unique_id’
y_cl4 = y_cl4.with_columns(
pl.concat_str([pl.col(‘MaterialID’), pl.col(‘SalesOrg’), pl.col(‘DistrChan’), pl.col(‘CL4’)], separator=’_’).alias(‘unique_id’)
)
y_cl4 = y_cl4.rename({‘WeekDate’: ‘ds’, ‘OrderQuantity’: ‘y’}), some of the output {‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 9, 22, 0, 0), ‘EnsembleForecast’: 5691, ‘Ensemble-lo-95’: 3171, ‘Ensemble-hi-95’: 8212, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5528.330078125, ‘AutoETS-lo-95’: 4238.36279296875, ‘AutoETS-hi-95’: 6818.29736328125, ‘CES’: 6107.98779296875, ‘CES-lo-95’: 2193.064208984375, ‘CES-hi-95’: 10022.9111328125, ‘DynamicOptimizedTheta’: 5567.36328125, ‘DynamicOptimizedTheta-lo-95’: 3139.6455078125, ‘DynamicOptimizedTheta-hi-95’: 7995.0810546875}
{‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 9, 29, 0, 0), ‘EnsembleForecast’: 5260, ‘Ensemble-lo-95’: 2739, ‘Ensemble-hi-95’: 7780, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5528.716796875, ‘AutoETS-lo-95’: 4238.74951171875, ‘AutoETS-hi-95’: 6818.68408203125, ‘CES’: 4380.20947265625, ‘CES-lo-95’: 465.2858581542969, ‘CES-hi-95’: 8295.1328125, ‘DynamicOptimizedTheta’: 5567.37158203125, ‘DynamicOptimizedTheta-lo-95’: 3139.65380859375, ‘DynamicOptimizedTheta-hi-95’: 7995.08935546875}
{‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 10, 6, 0, 0), ‘EnsembleForecast’: 5238, ‘Ensemble-lo-95’: 2717, ‘Ensemble-hi-95’: 7758, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5529.08837890625, ‘AutoETS-lo-95’: 4239.12109375, ‘AutoETS-hi-95’: 6819.0556640625, ‘CES’: 4292.49072265625, ‘CES-lo-95’: 377.5670166015625, ‘CES-hi-95’: 8207.4140625, ‘DynamicOptimizedTheta’: 5567.3798828125, ‘DynamicOptimizedTheta-lo-95’: 3139.662109375, ‘DynamicOptimizedTheta-hi-95’: 7995.09765625}
{‘unique_id’: ‘6922332’, ‘ds’: datetime.datetime(2025, 10, 13, 0, 0), ‘EnsembleForecast’: 5165, ‘Ensemble-lo-95’: 2645, ‘Ensemble-hi-95’: 7685, ‘AutoARIMA’: 5561.7099609375, ‘AutoARIMA-lo-95’: 3113.181396484375, ‘AutoARIMA-hi-95’: 8010.23876953125, ‘AutoETS’: 5529.4462890625, ‘AutoETS-lo-95’: 4239.47900390625, ‘AutoETS-hi-95’: 6819.41357421875, ‘CES’: 4001.488037109375, ‘CES-lo-95’: 86.56428527832031, ‘CES-hi-95’: 7916.41162109375, ‘DynamicOptimizedTheta’: 5567.38818359375, ‘DynamicOptimizedTheta-lo-95’: 3139.67041015625, ‘DynamicOptimizedTheta-hi-95’: 7995.10595703125} is there a way to break the unqiue id in the 4 columns in the output again? so instead of ‘unique_id’: …, it would be material_id: …, sales_org:. …, distrchan: …, cl4: …, and also the ‘ds’ be rename back to ‘WeekDate’
This code snippet splits the 'unique_id' column back into its original components by splitting the string on the _ character and then renames the 'ds' column to 'WeekDate'. After these operations, it prints out the modified forecasts.
Please ensure you have the latest versions of the necessary libraries installed since their APIs might have changed after my last update. If you encounter any attribute errors or other exceptions, it might be worth checking the current documentation for the version of Polars you're using to confirm method names and class attributes.
Place this code right before you create and print forecasts_list in your existing script. Essentially, you are manipulating forecasts_df one last time to reverse the concatenation and renaming the date column before converting it to a list of dictionaries for printing or further processing.
WeekDate
Here is how you can integrate these steps and then reorder the columns. Just make sure to adjust the column names according to the outcome you expect after splitting unique_id.
# ...previous code...
# Split the 'unique_id' into its original components and rename 'ds' to 'WeekDate'.
forecasts_df = forecasts_df.with_columns([
forecasts_df['unique_id'].str.split('_').alias("split_id")
]).with_columns([
pl.col('split_id').arr.get(0).alias('MaterialID'),
pl.col('split_id').arr.get(1).alias('SalesOrg'),
pl.col('split_id').arr.get(2).alias('DistrChan'),
pl.col('split_id').arr.get(3).alias('CL4')
]).drop(['unique_id', 'split_id']).rename({'ds': 'WeekDate'})
# Reorder and select the columns appropriately.
forecasts_df = forecasts_df.select([
"MaterialID",
"SalesOrg",
"DistrChan",
"CL4",
"WeekDate",
"EnsembleForecast",
"Ensemble-lo-95",
"Ensemble-hi-95",
"ADIDA",
"ADIDA-lo-95",
"ADIDA-hi-95",
"CrostonClassic",
"CrostonClassic-lo-95",
"CrostonClassic-hi-95",
"IMAPA",
"IMAPA-lo-95",
"IMAPA-hi-95",
"TSB",
"TSB-lo-95",
"TSB-hi-95"
])
# ...code to convert to list and print...
Remember to replace "ADIDA", "CrostonClassic", "IMAPA", "TSB", and related prediction interval columns with the correct model name columns you have in your actual forecasts_df, because they might differ based on the models you've used in your ensemble.
Adjust the column names in the reordering block to reflect the actual column names in forecasts_df after you've performed the modification on unique_id and WeekDate.
is my code correct now from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, AutoETS, DynamicOptimizedTheta
from statsforecast.utils import ConformalIntervals
import numpy as np
import polars as pl
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
Print the list
for forecast in forecasts_list:
print(forecast)
Your code seems mostly correct based on the provided context and objective. However, there are a couple of things to double-check:
Ensure that the forecast dataframe columns—like "AutoARIMA", "AutoETS", "DynamicOptimizedTheta" and their associated prediction intervals—accurately reflect what is generated by the StatsForecast module. The names should match the output columns of your forecasting models.
When you reorder the columns at the end, make sure that the names are correct and reflect your actual dataframe columns.
Here's a slightly modified version of the tail end of your code, with more explicit column selection:
# ...previous code...
# Split the unique_id concat into the original columns
forecasts_df = forecasts_df.with_column(pl.col('unique_id').str.split('_').alias('split_id'))
forecasts_df = forecasts_df.with_columns([
pl.col('split_id').arr.get(0).alias('MaterialID'),
pl.col('split_id').arr.get(1).alias('SalesOrg'),
pl.col('split_id').arr.get(2).alias('DistrChan'),
pl.col('split_id').arr.get(3).alias('CL4')
]).drop(['unique_id', 'split_id'])
# Rename 'ds' to 'WeekDate'
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Reorder the columns
forecasts_df = forecasts_df.select([
"MaterialID",
"SalesOrg",
"DistrChan",
"CL4",
"WeekDate",
"EnsembleForecast",
"Ensemble-lo-95",
"Ensemble-hi-95",
"AutoARIMA",
"AutoARIMA-lo-95",
"AutoARIMA-hi-95",
"AutoETS",
"AutoETS-lo-95",
"AutoETS-hi-95",
"DynamicOptimizedTheta",
"DynamicOptimizedTheta-lo-95",
"DynamicOptimizedTheta-hi-95"
])
# Create an empty list
forecasts_list = []
# Append each row to the list
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
# Print the list
for forecast in forecasts_list:
print(forecast)
Additionally, in your code, you are using pl.Series for creating a new column, but with Polars, you can directly use .with_column() method to get the same result:
# Create columns for the ensemble forecast and its prediction intervals directly
forecasts_df = forecasts_df.with_columns([
ensemble_forecast.alias('EnsembleForecast'),
ensemble_lo_95.alias('Ensemble-lo-95'),
ensemble_hi_95.alias('Ensemble-hi-95')
])
And remember:
Make sure that y_cl4_filtered and y_cl4_fit_1 are the dataframes you intend to pass to the forecasting functions.
Ensure that the cross_validation and forecast methods of StatsForecast are used correctly according to their latest documentation.
Ensure that 'WeekDate' and 'OrderQuantity' have the expected formats before and after forecasting to prevent any discrepancies.
how about now from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, AutoETS, DynamicOptimizedTheta
from statsforecast.utils import ConformalIntervals
import numpy as np
import polars as pl
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
Print the list
for forecast in forecasts_list:
print(forecast)
WeekDate
unique_id
ds
If you encounter any errors during execution, consider breaking the script down and testing each section to ensure everything works step-by-step. Since I can't see the actual data and model outputs, I can only confirm that your code structure is logical and follows typical Polars usage patterns. If there are any discrepancies in naming or expected outputs, you will need to adjust the code accordingly.
SchemaError: invalid series dtype: expected FixedSizeList, got list[str]
Replace your current splitting and column expansion code with the above snippet. It directly creates the new columns MaterialID, SalesOrg, DistrChan, and CL4 from the unique_id without needing to create an intermediate split_id column, avoiding the mentioned error.
Please make sure you are working with the latest libraries, since sometimes serialization formats change, and what used to work might not function the same way with an updated version of a library. Additionally, ensure that any other part of your code aligns with your data and expected outcomes.
is this correct from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, AutoETS, DynamicOptimizedTheta
from statsforecast.utils import ConformalIntervals
import numpy as np
import polars as pl
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
Print the list
for forecast in forecasts_list:
print(forecast)
When dropping columns, you mention drop('unique_id'), but you should also drop 'split_id' if you decided to keep the intermediate step.
The alias 'MaterialID' should match between where it's defined and the reordering section.
Here's the corrected portion of your code:
# ...
# Split the unique_id concat into the original columns
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('_').arr.get(0).alias('MaterialID'), # Corrected split delimiter and alias
pl.col('unique_id').str.split('_').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('_').arr.get(2).alias('DistrChan'),
pl.col('unique_id').str.split('_').arr.get(3).alias('CL4')
]).drop('unique_id')
# Rename 'ds' to 'WeekDate'
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Reorder the columns
forecasts_df = forecasts_df.select([
"MaterialID", # Matching alias used in the split
"SalesOrg",
"DistrChan",
"CL4",
"WeekDate",
"EnsembleForecast",
"Ensemble-lo-95",
"Ensemble-hi-95",
"AutoARIMA",
"AutoARIMA-lo-95",
"AutoARIMA-hi-95",
"AutoETS",
"AutoETS-lo-95",
"AutoETS-hi-95",
"DynamicOptimizedTheta",
"DynamicOptimizedTheta-lo-95",
"DynamicOptimizedTheta-hi-95"
])
# ...
# Print the list
for forecast in forecasts_list:
print(forecast)
Remember to carefully inspect your data at each step, to ensure that each operation works as intended and the data looks correct. It's also a good idea to handle any exceptions or edge cases that might occur due to unexpected data.
When you're splitting the unique_id, use the correct delimiter that was used to join the four original columns into the unique_id. Then, define all your columns in the .select() function to create your final DataFrame.
Remember to use .alias() method to rename and choose the columns you want to keep in the DataFrame for proper column order. Also, make sure any intermediate columns created for transformations are dropped if they are no longer needed.
select
Here's a completed example:
# Split the unique_id concat into the original columns
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('_').arr.get(0).alias('MaterialID'),
pl.col('unique_id').str.split('_').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('_').arr.get(2).alias('DistrChan'),
pl.col('unique_id').str.split('_').arr.get(3).alias('CL4')
]).drop('unique_id')
# Rename ‘ds’ to ‘WeekDate’
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Reorder the columns
forecasts_df = forecasts_df.select([
"MaterialID",
"SalesOrg",
"DistrChan",
"CL4",
"WeekDate",
# ...include all other columns you want to keep in the same order you prefer...
])
Remember to include all other columns that you need in the DataFrame in the select method. If you have additional predictive columns or metrics that you want in the final DataFrame, list them in the order you want them to appear.
Here's how you would include some of the other columns:
forecasts_df = forecasts_df.select([
"MaterialID",
"SalesOrg",
"DistrChan",
"CL4",
"WeekDate",
"EnsembleForecast",
"Ensemble-lo-95",
"Ensemble-hi-95",
# Include rest of your predictive model columns, e.g.
"AutoARIMA",
"AutoARIMA-lo-95",
"AutoARIMA-hi-95",
"AutoETS",
"AutoETS-lo-95",
"AutoETS-hi-95",
"DynamicOptimizedTheta",
"DynamicOptimizedTheta-lo-95",
"DynamicOptimizedTheta-hi-95",
# ...any other columns...
])
Please ensure that you are including all the relevant columns you'd like to be in the final DataFrame after reordering.
I apologize for the inconvenience. Let's try to debug the issue together.
First, could you please provide more information about the error message you're encountering? Typically, Python errors include a traceback that leads you to the line where the error occurred and gives an explanation of what went wrong. This information would be very helpful in diagnosing the problem.
Meanwhile, let's go through some common reasons why you might be encountering an error:
Column Names Mismatch: Make sure that the names of the columns you are using to split unique_id and rename ds to WeekDate reflect exactly those used in your dataframe and that they are consistent with the ones you have in your select statement.
Redundant Operations: If you are using Polars, there is no need to create an intermediate Series to add a new column to the DataFrame; you can directly use with_column or chain the operations.
Data Type Issues: You may encounter errors when casting data types (e.g., from float to integer) if there are NaN or infinite values that cannot be cast to integers.
Here is a general form of how your code should look like. This assumes there are no NaN values that might cause issues during data type casting:
# Round the ensemble forecast and prediction intervals and convert to integer
# Ensure that there are no NaN or infinite values before this step
forecasts_df = forecasts_df.with_columns([
pl.col('EnsembleForecast').round().cast(pl.Int32).alias('EnsembleForecast'),
pl.col('Ensemble-lo-95').round().cast(pl.Int32).alias('Ensemble-lo-95'),
pl.col('Ensemble-hi-95').round().cast(pl.Int32).alias('Ensemble-hi-95')
])
# Basic check: print out the dataframe to see if above operations are successful
# print(forecasts_df)
# Split the `unique_id` concat into the original columns
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('_').arr.get(0).alias('MaterialID'),
pl.col('unique_id').str.split('_').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('_').arr.get(2).alias('DistrChan'),
pl.col('unique_id').str.split('_').arr.get(3).alias('CL4')
]).drop('unique_id')
# Basic check: print out the dataframe to see if above operations are successful
# print(forecasts_df)
# Rename `ds` to `WeekDate`
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Reorder the columns
forecasts_df = forecasts_df.select([
'MaterialID',
'SalesOrg',
'DistrChan',
'CL4',
'WeekDate',
'EnsembleForecast',
'Ensemble-lo-95',
'Ensemble-hi-95'
# Add other columns as necessary...
])
# Basic check: print out the final dataframe to see if all operations are correct
# print(forecasts_df)
Make sure to comment out or remove the print statements when running this in a production environment, as they're only used for debugging purposes.
Please try running the above code, and if you encounter an error, provide the specific error message. If there's a different issue such as NaNs or incompatible data types, we'll need to address that specifically.
SchemaError: invalid series dtype: expected FixedSizeList, got list[str]
Here is the revised code snippet to handle the splitting:
# Ensure you have the latest polars installed
# !pip install -U polars
import polars as pl
# First, try this block on its own to check if it executes without an error.
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.split('_').arr.get(0).alias('MaterialID'),
pl.col('unique_id').str.split('_').arr.get(1).alias('SalesOrg'),
pl.col('unique_id').str.split('_').arr.get(2).alias('DistrChan'),
pl.col('unique_id').str.split('_').arr.get(3).alias('CL4')
])
forecasts_df = forecasts_df.drop('unique_id')
# Rename ‘ds’ to ‘WeekDate’
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# If the above block runs without an error, execute the rest of your code.
# Continue with the rest of your pipeline
# ...
Please run this block alone at first to ensure it completes without an error. If successful without an error, you can continue with the rest of your code. Ensuring you have the most recent version of polars could potentially resolve such issues. You can update polars with pip install -U polars.
If the error persists even after trying the above code, please let me know and provide details about the version of the polars library you are using and any additional context that could be relevant.
Based on your last message and the structure of unique_id, here's an updated approach that assumes unique_id is a single string composed of MaterialID, SalesOrg, DistrChan, and CL4, concatenated with underscores.
Here's how you might extract the components correctly:
import polars as pl
# If needed, first ensure that y_cl4 is available for forecasting tasks:
# y_cl4 = ...
forecasts_df = forecasts_df.with_columns([
pl.col('unique_id').str.extract(r'(\d+)_([A-Za-z0-9]+)_(\d+)_([A-Za-z0-9]+)', 4)
])
forecasts_df = forecasts_df.rename({
'literal_0': 'MaterialID',
'literal_1': 'SalesOrg',
'literal_2': 'DistrChan',
'literal_3': 'CL4'
})
# Cast the extracted 'MaterialID' and 'DistrChan' back to integers
forecasts_df = forecasts_df.with_columns([
pl.col('MaterialID').cast(pl.Int64),
pl.col('DistrChan').cast(pl.Int64)
])
# Continue with the rest of your pipeline
# ...
In the above code, str.extract is used with a regex pattern to split unique_id into captures that are accordingly renamed and cast to the appropriate types. These steps replace the previous split and aliasing steps and should help resolve the SchemaError.
The regex pattern r'(\d+)_([A-Za-z0-9]+)_(\d+)_([A-Za-z0-9]+)' aims to capture the numeric and alphanumeric parts separated by underscores. It assumes no underscores within individual components. If this assumption holds, then this should correctly split your unique_id into its original components.
Be sure to adjust the pattern to match the exact format of your unique_id. If your MaterialID or DistrChan can contain leading zeros that are significant or if there are other variations, you may need a different casting type or approach.
If this update doesn't resolve your issue, or if there are significant format variations in unique_id, please provide further details or examples of the unique_id format, and we can refine the solution.
A few notes on the changes:
We are using str.split("_") to split the unique_id and then arr.get(i) to select each piece of the split string.
We cast MaterialID and DistrChan back to integers using .cast(pl.Int64) because you indicated that they are originally integers.
No casting is necessary for SalesOrg and CL4 as they are strings.
We remove the unique_id column afterward since it is redundant now.
Make sure to execute this on the DataFrame that has the unique_id after you've done the rest of the forecasting and have the unique_id to split.
With this correction, please try running your code again. If you run into any additional issues, please let me know!
Error originated just after this operation:
DF ["unique_id", "ds", "AutoARIMA", "AutoARIMA-lo-95"]; PROJECT */14 COLUMNS; SELECTION: "None"
'unique_id'
Please run this updated code and it should execute without any such column-not-found errors. This error underscores the importance of accurately naming columns, as a small typo can lead to these kinds of exceptions.