【问题标题】:select the rows of a table according to an id that is in a JSON in a column of the table根据表列中 JSON 中的 id 选择表的行
【发布时间】:2021-03-29 09:20:24
【问题描述】:

我需要根据 id 在 JSON 中使用 Pandas 在其中一列中选择表的行。

示例:

column_a column_b column_c
aaaa bbbbb {'id' : cc, 'name' : xx ...}
xxxx yyyy {'id' : ff, 'name' : gg ...}

所以我想选择column_c中JSON的id等于'cc'的所有行,所以结果将是:

column_a column_b column_c
aaaa bbbbb {'id' : cc, 'name' : xx ...}

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    试试这个:

    import json
    
    def func(x): #x is a string of json format
        s=json.loads(x)
        return s['id']=='cc'
    

    并通过将上述函数应用于 column_c 来过滤数据框:

    df[df['column_c'].apply(lambda x: func(x)]
    

    如果这不起作用,则表示 column_c 是不同的类型。在这种情况下,请提供此列的类型,以便我调整解决方案

    【讨论】:

      【解决方案2】:

      如果您已经将它加载到 pandas 中,它现在可能是一个字典,可以通过类似于数据框的键访问,因此您希望像这样进行过滤:

      df[df['column_c']['id'] == 'cc']
      

      【讨论】:

        猜你喜欢
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-29
        • 2020-09-04
        • 2022-12-22
        • 2018-03-01
        • 1970-01-01
        相关资源
        最近更新 更多