Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

don't understand ValueError: Must have equal len keys and value when setting with an iterable in Python

I’m working in a ML script and I want to change the values of a column by the same, but instead of string, stored as an array. Now the data is stored like this: ’31-2′, and I want to store as ‘[31,2]’. However, I get ValueError: Must have equal len keys and value when setting with an iterable, and I don’t understand why. I’m using Pandas library.

Original data: enter image description here
Transformation I want: enter image description here

for i in range(0,len(ml_dataset)):
      var = str(ml_dataset.loc[i, "Layout"]).split("-")
      ml_dataset.loc[i, "Layout"] = var

The error raises in the last sentence. I have many columns and have no problems with that sentence, but for this, when trying to store as an array I get the problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have read about .apply() method and lambda expressions, but no idea how to use them in my case.

Thank you very much!

>Solution :

IIUC use Series.str.split with casting values to strings:

ml_dataset = pd.DataFrame({'Layout':['31-2','20', 5]})

ml_dataset["Layout"] = ml_dataset["Layout"].astype(str).str.split("-")
print (ml_dataset)
    Layout
0  [31, 2]
1     [20]
2      [5]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading