【问题标题】:python pandas Data frame column has string value looks like list of dictionaries?python pandas Dataframe 列的字符串值看起来像字典列表?
【发布时间】:2020-02-29 06:45:49
【问题描述】:

我有一个数据框列,其中包含字符串值(已编辑) 数据框列的类型是字符串但(已编辑) 它的值看起来像字典列表(已编辑) 如何从该字符串中提取一些键值? 此 STRING 值类似于字典列表。

当键“job”的值为“Director”时,如何提取 name 键的值?

[{
        'credit_id': '549e9edcc3a3682f2300824b',
        'department': 'Camera',
        'gender': 2,
        'id': 473,
        'job': 'Additional Photography',
        'name': 'Brian Tufano',
        'profile_path': None
    }, {
        'credit_id': '52fe4214c3a36847f8002595',
        'department': 'Directing',
        'gender': 2,
        'id': 578,
        'job': 'Director',
        'name': 'Ridley Scott',
        'profile_path': '/oTAL0z0vsjipCruxXUsDUIieuhk.jpg'
    }, {
        'credit_id': '52fe4214c3a36847f800259b',
        'department': 'Production',
        'gender': 2,
        'id': 581,
        'job': 'Producer',
        'name': 'Michael Deeley',
        'profile_path': None
    }, {
        'credit_id': '52fe4214c3a36847f800263f',
        'department': 'Writing',
        'gender': 2,
        'id': 584,
        'job': 'Novel',
        'name': 'Philip K. Dick',
        'profile_path': '/jDOKJN8SQ17QsJ7omv4yBNZi7XY.jpg'
    }, {
        'credit_id': '549e9f85c3a3685542004c7b',
        'department': 'Crew',
        'gender': 2,
        'id': 584,
        'job': 'Thanks',
        'name': 'Philip K. Dick',
        'profile_path': '/jDOKJN8SQ17QsJ7omv4yBNZi7XY.jpg'
    }, {
        'credit_id': '52fe4214c3a36847f800261b',
        'department': 'Writing',
        'gender': 2,
        'id': 583,
        'job': 'Screenplay',
        'name': 'Hampton Fancher',
        'profile_path': '/lrGecnLhzjzgwjKHvrmYtRAqOsP.jpg'
    }
]

【问题讨论】:

    标签: string pandas list dataframe dictionary


    【解决方案1】:
    import pandas as pd
    df =pd.DataFrame(LIST)
    Name=df['name'][df['job']=="Director"]
    print('Name =',Name)
    

    【讨论】:

    • 欢迎来到 StackOverflow!请不要只提供代码 - 尝试解释它的作用。您还应该使用多行代码框(三个反引号)。
    • 扩展 @finnmglas 的评论,纯代码的答案可能对 OP 有所帮助,但它们通常对后来遇到类似问题的人没有帮助。
    【解决方案2】:

    您可以通过将列表转换为 pandas 数据框来实现此目的: pandas.DataFrame.

    import pandas as pd
    df =pd.DataFrame(yourList)    
    df['name'][df['job']=="Director"] # you will get a series of all the names matching your condition.
    

    或者另一种方法是使用 .loc[]

    df.loc[df["job"]=="Director",["name"]] # You will get a dataframe with name column having all the names matching the condition.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-20
      • 2019-01-05
      • 2013-12-13
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多