从 pandas 到 Json 键

From pandas to Json with keys

我有一个包含 11 行和 1 列的数据框 df。在每一行中,我都有一个数组,我将其转换为 json 但为数组中的每个条目分配一个键。

例如,

                                                   0

 0     [1.234,1.234,2.1123,4.32212,1.2231,2.55323,1.4421]
 1     [2.21,1.234,1.31,3.121,2.22,2.32322,0.8873]

上面的 DataFrame 应该变成相同的 DataFrame 但在条目中有 json 数据:

                                                      0

 0     {"0":1.234,"1":1.234,"2":2.1123,"3":4.32212,"4"1.2231,"5"2.55323,"6": 
        1.4421}
 1   {"0":2.21,"1":1.234,"2":1.31,"3":3.121,"4":2.22,"5":2.32322,"6":0.8873}

提前致谢。

使用apply方法遍历列单元格;对于每个项目(列表),使用 enumerate 添加索引(键),然后将其转换为字典:

df['0'].apply(lambda lst: dict(enumerate(lst)))

#0    {0: 1.234, 1: 1.234, 2: 2.1123, 3: 4.32212, 4:...
#1    {0: 2.21, 1: 1.234, 2: 1.31, 3: 3.121, 4: 2.22...
#Name: 0, dtype: object