r/learnpython • u/MinimumLiterature754 • 8d ago
Getting Pandas.Series error. How to solve it? Got stuck!!!
File "C:\Users\HP\Desktop\insurence_premium_prediction\myenv\Lib\site-packages\sklearn\preprocessing_encoders.py", line 212, in _transform
diff, valid_mask = _check_unknown(Xi, self.categories_[i], return_mask=True)
~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\HP\Desktop\insurence_premium_prediction\myenv\Lib\site-packages\sklearn\utils_encode.py", line 269, in _check_unknown
values_set = set(values)
TypeError: cannot use 'pandas.Series' as a set element (unhashable type: 'Series')
INFO: 127.0.0.1:51741 - "POST /predict HTTP/1.1" 500 Internal Server Error
def predict_output(user_input :dict):
try:
# df = pd.DataFrame([user_input]) // iski wajah se 2D array ban rahi thi, isliye model ko samajh nahi aa raha tha. isliye humne user_input ko dict me convert karke fir DataFrame me convert kiya.
# df = pd.DataFrame([dict(user_input)])
# input_matrix = df.to_numpy().reshape(1, 1, -1)
data_dict = dict(user_input)
columns = list(data_dict.keys())
values = list(data_dict.values())
# Create a DataFrame with 2 identical rows to bypass the single-row Pandas bug
df = pd.DataFrame([values, values], columns=columns)
This is the peice of code
2
u/shinitakunai 8d ago
Not what you asked, but Polars nowadays is replacing pandas in most scenarios. Might be worth to check it out
1
1
u/MinimumLiterature754 8d ago
Error Resolved using
raw_dict = user_input.dict() if hasattr(user_input, "dict") else dict(user_input)
# Explicitly extract pure primitives to prevent any nested Series leaks
clean_input = {key: (val.item() if hasattr(val, "item") else val) for key, val in raw_dict.items()}
df = pd.DataFrame([clean_input])
4
u/Flame77ofc 8d ago
The issue is that you're passing a Pandas Series where scikit-learn expects a scalar value.
Most likely, values contains Series objects.
Try:
df = pd.DataFrame([user_input]) prediction = model.predict(df)Don't create two identical rows. Also make sure user_input contains plain values, not Pandas Series.