Python Forum
Assigning conditional values in Pandas - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Assigning conditional values in Pandas (/thread-41296.html)



Assigning conditional values in Pandas - Scott - Dec-14-2023

Hi everyone,

I am playing around with some old code from online and am getting an error:

for dataset in train_test_data:
    dataset.loc[ dataset['Age'] <= 16, 'Age'] = 0,
    dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 26), 'Age'] = 1,
    dataset.loc[(dataset['Age'] > 26) & (dataset['Age'] <= 36), 'Age'] = 2,
    dataset.loc[(dataset['Age'] > 36) & (dataset['Age'] <= 62), 'Age'] = 3,
    dataset.loc[ dataset['Age'] > 62, 'Age'] = 4
ValueError: Must have equal len keys and value when setting with an iterable

Does anyone know how to assign conditional values in pandas?

Thanks
Scott


RE: Assigning conditional values in Pandas - Larz60+ - Dec-15-2023

you must elaborate, there's not enough information here.
what are the error codes?
what does train_test_data structure look like, etc.
Also, code needs to be a snippet that can be run, or at least, one where all inputs and outputs are visable.


RE: Assigning conditional values in Pandas - Scott - Dec-18-2023

Hi,

here is the complete code in github. It was written by someone years ago and I'm guessing there has been some changes to python since then.

https://github.com/minsuk-heo/kaggle-titanic/blob/master/titanic-solution.ipynb

If you run this script you'll get the same error at the point in code above.

Thanks


RE: Assigning conditional values in Pandas - Larz60+ - Dec-19-2023

This code was written using Iron python link here
There shouldn't be any massive changes since 2017.
I present this link as an aid.