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.
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]