Home > Net >  Python DataFrame display single column value
Python DataFrame display single column value

Time:04-29

Using below json data, trying to extract the bookId like [ 0,6,13] as list. below code is not working for me.

import pandas as pd
data='''{
        "bookIds": [
            {
                "bookId": 0
            },
            {
                "bookId": 6
            },
            {
                "bookId": 13
            }]
    }'''


    df = pd.read_json(data)    
    print(df['bookIds']['bookId'])

Error

 raise KeyError(key)
KeyError: 'bookId'

How can I extract only bookID using datafarme?

Thanks

CodePudding user response:

read_json creates a single column DataFrame with dict values. You can use str.get to access the values in the dicts in the column "bookIds":

out = pd.read_json(data)['bookIds'].str.get('bookId').tolist()

Output:

[0, 6, 13]
  • Related