【问题标题】:DataFrame column of lists to dictionaries字典列表的 DataFrame 列
【发布时间】:2021-02-11 17:40:26
【问题描述】:
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, ...

【问题讨论】:

  • 之前的帖子是什么?您能否添加更多上下文以帮助我们更好地理解
  • 没明白逻辑
  • 这里是previous post

标签: python list dataframe dictionary


【解决方案1】:

假设你的系列对象被称为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

我从your previous post 获得了列名。

【讨论】:

  • 很高兴随时提供帮助。
【解决方案2】:
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: ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 2022-10-13
    • 2022-01-20
    • 2019-06-07
    • 2021-10-04
    • 1970-01-01
    • 2016-07-24
    • 2017-12-26
    相关资源
    最近更新 更多