DataFrame列的列表到字典


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

我在之前的帖子中犯了一个错误,他确实给了我正确的答案,但显然我需要字典的形式。

例如,第0行需要看起来像:

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

假设您的系列对象名为lists,根据上面显示的输出,您可以尝试-

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

我从你以前的帖子中得到了列名。

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

相关内容

  • 没有找到相关文章

最新更新