如何在数据帧中修改听写?

2024-10-02 00:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在数据帧中修改列表值?我正在尝试调整JSON接收到的数据,数据帧如下:

Dataframe df:
    id    options
0    0     [{'a':1 ,'b':2, 'c':3, 'd':4}]
1    1     [{'a':5 ,'b':6, 'c':7, 'd':8}] 
2    2     [{'a':9 ,'b':10, 'c':11, 'd':12}]

如果我只想在options中使用'a'和'c'键/值,如何修改datafames?预期结果将是:

Dataframe df:
    id    options
0    0     [{'a':1 ,'c':3}]
1    1     [{'a':5 ,'c':7}] 
2    2     [{'a':9 ,'c':11}]

Tags: 数据idjsondataframedf列表optionsdatafames
2条回答

下面是一个使用列表理解创建仅包含特定键的新词典的示例:

df['options'] = [[{'a': x[0]['a'], 'c': x[0]['c']}] for x in df['options']]

您只需apply一个修改条目的函数:

>>> df.options = df.options.apply(lambda x: [{k: v for k, v in x[0].items() if k in ('a', 'c')}])
>>> df
   id              options
0   0   [{'a': 1, 'c': 3}]
1   1   [{'a': 5, 'c': 7}]
2   2  [{'a': 9, 'c': 11}]

相关问题 更多 >

    热门问题