user13110231
user13110231

Reputation:

DataFrame column of lists to dictionaries

lists
Out[140]: 
0          [1, 1, 1, 1, 1, 1, 2, 3, 6, 4, 4, 4, 5, 5, 5, ...
1          [1, 1, 1, 1, 1, 1, 2, 3, 6, 4, 4, 4, 5, 5, 5, ...
2          [1, 1, 1, 1, 1, 1, 2, 3, 6, 4, 4, 5, 5, 5, 5, ...
3          [1, 1, 1, 1, 1, 1, 2, 3, 6, 4, 4, 5, 5, 5, 5, ...
4          [1, 1, 1, 1, 1, 1, 2, 3, 6, 4, 4, 4, 5, 5, 5, ...
                                 ...                        
43245                         [2, 3, 6, 4, 4, 4, 5, 5, 5, 5]
43246                               [2, 3, 6, 4, 4, 5, 5, 5]
43247                               [2, 3, 6, 4, 4, 5, 5, 5]
43248                                     [2, 3, 6, 4, 5, 5]
ln_dict                 {0: 2, 1: 3, 2: 6, 3: 4, 4: 5, 5: 5}
Name: Ln, Length: 43250, dtype: object

I made a mistake in my previous post, he did give me the correct answer, but apparently i need it in the form of a dictionary.

For instance, row 0 needs to look like:

0          {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 2, 8: 3, 9: 6, 10: 4, 11: 4, 12: 4, 13: 5, ...

Upvotes: 1

Views: 40

Answers (2)

Akshay Sehgal
Akshay Sehgal

Reputation: 19332

Assuming that your series object is called lists, as per the output you show above, you can try this -

lists.apply(lambda x: dict(enumerate(x,1)))
0    {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 2, 8: ...
1    {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 2, 8: ...
2    {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 2, 8: ...
3    {1: 2, 2: 3, 3: 6, 4: 4, 5: 4, 6: 4, 7: 5, 8: ...
4     {1: 2, 2: 3, 3: 6, 4: 4, 5: 4, 6: 5, 7: 5, 8: 5}
5     {1: 2, 2: 3, 3: 6, 4: 4, 5: 4, 6: 5, 7: 5, 8: 5}
6                 {1: 2, 2: 3, 3: 6, 4: 4, 5: 5, 6: 5}
dtype: object

I got the column name from your previous post.

Upvotes: 1

Epsi95
Epsi95

Reputation: 9047

df = pd.DataFrame([[[1, 1, 1, 1, 1, 1, 2, 3, 6, 4, 4, 4, 5, 5, 5]],[[2, 3, 6, 4, 4, 4, 5, 5, 5, 5]]], columns=['a'])

df['a'] = df.apply(lambda x: dict(zip(range(1, len(x['a'])+1),x['a'])))
    a
0   {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 2, 8: ...
1   {1: 2, 2: 3, 3: 6, 4: 4, 5: 4, 6: 4, 7: 5, 8: ...

Upvotes: 1

Related Questions