正在分析中的数据json.loads文件(),在python中

2024-09-28 20:45:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图分析一个网站的数据。我解析了HTML以获得json数据json.loads文件(). 你知道吗

data = json.loads(soup.find('script', type='application/ld+json').text)

现在我只剩下如下数据:

data = """
{'aggregateRating': {'reviewCount': 1691, 
                     '@type'      : 'AggregateRating', 
                     'ratingValue': 4.0}, 
 'review': [{'reviewRating' : {'ratingValue': 5}, 
               'datePublished': '2017-10-31', 
               'description'  : "I had a chance to see the Lakers ...", 
               'author'       : 'Andre W.'}]
}
""""

我有兴趣返回“review”数组中reviewRating的“ratingValue”整数。当我运行此脚本时:

pd.DataFrame(data['review'], columns = ['reviewRating'])

我明白了:

    reviewRating
0   {'ratingValue': 5}

相反,我希望获得以下形式的数据:

    ratingValue
0   5

我尝试过各种各样的变化,比如

pd.DataFrame(data['review'], columns = ['reviewRating']['ratingValue'])
pd.DataFrame(data['review'], columns = ['reviewRating'][['ratingValue']])
pd.DataFrame(data['review']['reviewRating'], columns = ['ratingValue'])

但我肯定我不了解数据的底层结构,或者说熊猫。你知道吗

因此,我最好将{ratingValue':5}清除为字符串,以便留下感兴趣的整数,还是有一种简单的方法来创建一个整数值为“ratingValue”的数据帧?你知道吗

谢谢。你知道吗


Tags: columns文件数据jsondataframedata网站html
1条回答
网友
1楼 · 发布于 2024-09-28 20:45:35

如果使用来自pandas.io.jsonjson_normalize,则可以直接从json创建数据帧。你知道吗

使用您的示例数据,我能够输出:

>>> frame = json_normalize(data)

     author datePublished                           description  \
0  Andre W.    2017-10-31  I had a chance to see the Lakers ...

   reviewRating.ratingValue
0                         5

然后您可以使用以下方法访问额定值:

frame.at[0, 'reviewRating.ratingValue'] # which should give you 5

相关问题 更多 >