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

Length of values (1) does not match length of index (156) in pandas

I am trying to convert a column to dictionary key value pair in pandas.

Input:

ID  col1
1   DAY=20220524
2   DAY=20220525
3   NOON=20220525

Expected Output:

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

ID  col1
1   {"DAY":20220524}
2   {"DAY":20220525}
3   {"NOON":20220524}

I wrote below code to get dictionary key value pair.

df_csv[['txt1','txt2']] = df_csv.col1.str.split("=",expand=True)
df_csv['txt2']= df_csv['txt2'].astype(int)
df_csv['col1'] =pd.Series(df_csv.txt2.values,index=df_csv.txt1).to_dict()

with these I am getting the dictionary key value pair but just once and since I have 156 rows it gives me below error.

Length of values (1) does not match length of index (156) 

how do I iterate through all columns to get this dictionary key value pair and not just once?

>Solution :

This would work for your example:

df_csv.col1 = df_csv.col1.apply(lambda x: {x.split('=')[0]:int(x.split('=')[1])})

Input:

   ID           col1
0   1   DAY=20220524
1   2   DAY=20220525
2   3  NOON=20220525

Output:

   ID                col1
0   1   {'DAY': 20220524}
1   2   {'DAY': 20220525}
2   3  {'NOON': 20220525}
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