Home > Net >  create a dictionary of array for each cell within dataframe
create a dictionary of array for each cell within dataframe

Time:08-07

i have a dataframe with two columns of array.

Column 1
0        [254.0, 254.0, 254.0, 254.0, 254.0]
1        [254.0, 254.0, 254.0, 254.0, 254.0]
2        [254.0, 254.0, 254.0, 254.0, 254.0]
3        [254.0, 254.0, 254.0, 254.0, 254.0]
4        [254.0, 254.0, 254.0, 254.0, 254.0]

Column 2
0      [3.0, 4.0, 7.0, 1.0, 5.0]  
1      [3.0, 4.0, 7.0, 1.0, 5.0]  
2      [3.0, 4.0, 7.0, 1.0, 5.0]  
3      [3.0, 4.0, 7.0, 1.0, 5.0]  
4      [3.0, 4.0, 7.0, 1.0, 5.0] 

I am trying to create a third column where each cell looks like a dictionary of arrays. It would look like the following:

Column 3
0        {0:[254.0,3], 1:[254.0,4], 2:[254.0,7], 3:[254.0,1], 4:[254.0,5]}
1        {0:[254.0,3], 1:[254.0,4], 2:[254.0,7], 3:[254.0,1], 4:[254.0,5]}
2        {0:[254.0,3], 1:[254.0,4], 2:[254.0,7], 3:[254.0,1], 4:[254.0,5]}
3        {0:[254.0,3], 1:[254.0,4], 2:[254.0,7], 3:[254.0,1], 4:[254.0,5]}
4        {0:[254.0,3], 1:[254.0,4], 2:[254.0,7], 3:[254.0,1], 4:[254.0,5]}

how do i do this ?

CodePudding user response:

How about:

df['Column 3'] = df.apply(lambda x: dict(enumerate(zip(x['Column 1'], x['Column 2']))), axis=1)

CodePudding user response:

import pandas as pd

c1 = [[254.0, 254.0, 254.0, 254.0, 254.0],
[254.0, 254.0, 254.0, 254.0, 254.0],
[254.0, 254.0, 254.0, 254.0, 254.0],
[254.0, 254.0, 254.0, 254.0, 254.0],
[254.0, 254.0, 254.0, 254.0, 254.0]]

c2 = [[3.0, 4.0, 7.0, 1.0, 5.0],
[3.0, 4.0, 7.0, 1.0, 5.0], 
[3.0, 4.0, 7.0, 1.0, 5.0],
[3.0, 4.0, 7.0, 1.0, 5.0], 
[3.0, 4.0, 7.0, 1.0, 5.0]]

df = pd.DataFrame({'Column 1': c1, 'Column 2': c2})
df['Column 3'] = df.apply(lambda r: {i: [v1, v2] for i, (v1, v2) in enumerate(zip(r['Column 1'], r['Column 2']))}, axis=1)
df

prints

index Column 1 Column 2 Column 3
0 254,254,254,254,254 3,4,7,1,5 {0: [254.0, 3.0], 1: [254.0, 4.0], 2: [254.0, 7.0], 3: [254.0, 1.0], 4: [254.0, 5.0]}
1 254,254,254,254,254 3,4,7,1,5 {0: [254.0, 3.0], 1: [254.0, 4.0], 2: [254.0, 7.0], 3: [254.0, 1.0], 4: [254.0, 5.0]}
2 254,254,254,254,254 3,4,7,1,5 {0: [254.0, 3.0], 1: [254.0, 4.0], 2: [254.0, 7.0], 3: [254.0, 1.0], 4: [254.0, 5.0]}
3 254,254,254,254,254 3,4,7,1,5 {0: [254.0, 3.0], 1: [254.0, 4.0], 2: [254.0, 7.0], 3: [254.0, 1.0], 4: [254.0, 5.0]}
4 254,254,254,254,254 3,4,7,1,5 {0: [254.0, 3.0], 1: [254.0, 4.0], 2: [254.0, 7.0], 3: [254.0, 1.0], 4: [254.0, 5.0]}
  • Related