Python 和 Pandas : Find a dict within a list according to a key's value

标签 python pandas

我有一个如下所示的列表:

dict_list = [{'angle': 5.0,
              'basic_info': '111',
              'x': [1,2,3,4],
              'y': [3,2,1,4],},
            {'angle': 25.0,
              'basic_info': '111',
              'x': [1,2,3,4],
              'y': [3,1,5,2],},
            {'angle': 3.0,
              'basic_info': '111',
              'x': [1,2,3,4],
              'y': [1,1,4,1],},]

我想得到 dict 角度 25,我该怎么做?


更新:

与 Pandas 玩了一段时间后,我发现这可能是可能的

df = pd.DataFrame(dict_list)
temp = df.query("(angle ==25 )").T.to_dict()[temp.keys()[0]]
temp

返回

{'angle': 25.0, 'basic_info': '111', 'x': [1, 2, 3, 4], 'y': [3, 1, 5, 2]}

但这有点黑客。

最佳答案

假设字典中的每个角度都是唯一的,并且每个字典都包含键“角度”:

df = None
for sub_dict in dict_list:
    if sub_dict['angle'] == 25:
        df = pd.DataFrame({'x': sub_dict['x'], 'y': sub_dict['y']})
        break  # Stops after finding the first matching angle.
if df is not None:
    df.plot(x='x', y='y')

enter image description here

关于Python 和 Pandas : Find a dict within a list according to a key's value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908903/

相关文章:

python - 使用子进程时如何在 Python 中复制 tee 行为?

python - groupby 列同时显示其他列

python-3.x - 将一列替换为另一列,除非 Pandas 中另一列为 NaN

python - 字符串在 Pandas 数据框中包含python中的函数?

python - 如何在 for 循环中堆叠多个 pandas DataFrame

pandas - Seaborn:在热图上注释缺失值

python - 从抛物面镜检测图像中心?

python - 类型错误 : replace() takes no keyword arguments on changing timezone

python - 将数组转换为 float ,如何反转该过程?

python - 在 Pandas 中将列表转换为日期时间