Home > front end >  Length of values (1) does not match length of index (156) in pandas
Length of values (1) does not match length of index (156) in pandas

Time:05-28

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:

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?

CodePudding user response:

Let us do

df.col1 = [dict([tuple(x.split('='))])  for x in df.col1]
df
Out[91]: 
   ID                  col1
0   1   {'DAY': '20220524'}
1   2   {'DAY': '20220525'}
2   3  {'NOON': '20220525'}

CodePudding user response:

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}
  • Related