python:如何在数据帧中修改dictonary?

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

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

如何在数据帧中修改列表值?我正在尝试调整JSON接收到的数据,数据帧如下: 数据帧在一个列表中有“多个字典”

   Dataframe df:
        id    options
    0    0     [{'a':1 ,'b':2, 'c':3, 'd':4},{'a':5 ,'b':6, 'c':7, 'd':8}]
    1    1     [{'a':9 ,'b':10, 'c':11, 'd':12},{'a':13 ,'b':14, 'c':15, 'd':16}] 
    2    2     [{'a':9 ,'b':10, 'c':11, 'd':12},{'a':17 ,'b':18, 'c':19, 'd':20}]

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

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

我尝试过过滤,但无法将值赋给数据帧

for x in totaldf['options']:
    for y in x:
        y = {a: y[a], 'c': y['c']} ...?

Tags: 数据inidjsondataframedf列表for
2条回答
# An alternative vectorized solution.
df.options = df.options.apply(lambda x: [{k:v for k,v in e.items() if k in['a','c']} for e in x])

Out[398]: 
   id                                  options
0   0     [{'a': 1, 'c': 3}, {'a': 5, 'c': 7}]
1   1  [{'a': 9, 'c': 11}, {'a': 13, 'c': 15}]
2   2  [{'a': 9, 'c': 11}, {'a': 17, 'c': 19}]

使用嵌套列表:

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

如果您想使用for循环,它将类似于:

new_options = []
for x in df['options']:
    row = []
    for y in x:
        row.append({a: y[a], 'c': y['c']})
    new_options.append(row)

df['options'] = new_options

相关问题 更多 >

    热门问题