【问题标题】:How to get the dictionary value out of the list in a column?如何从列中的列表中获取字典值?
【发布时间】:2021-06-05 05:33:29
【问题描述】:

我在 pandas 数据框的列(“结果”)中有这些值。它似乎是列表中的字典。如何创建一个新列“标签”以从此“结果”列中获取值“POSITIVE”?

Orginal column 'results'
df=pd.DataFrame({
    'results':[[{'label': 'POSITIVE', 'score': 0.9989271759986877}],
              [{'label': 'POSITIVE', 'score': 0.9988722801208496}]
]})

我希望派生列“标签”看起来像这样。

df2=pd.DataFrame({
    'results':[[{'label': 'POSITIVE', 'score': 0.9989271759986877}],
              [{'label': 'POSITIVE', 'score': 0.9988722801208496}]],
    'label': ['POSITIVE','POSITIVE']
    })

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    我们可以使用 lambda 函数来获取 'results' 列每一行的(第一个)dict [0] 的 'label' 键,如下所示:

    import pandas as pd
    
    df = pd.DataFrame({
        'results':[[{'label': 'POSITIVE', 'score': 0.9989271759986877}],
                  [{'label': 'POSITIVE', 'score': 0.9988722801208496}]
    ]})
    
    df['label'] = df.apply(lambda row: row['results'][0]['label'], axis=1)
    print(df)
    

    输出:

                                                 results     label
    0  [{'label': 'POSITIVE', 'score': 0.998927175998...  POSITIVE
    1  [{'label': 'POSITIVE', 'score': 0.998872280120...  POSITIVE
    

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多