尝试使用 .loc 在另一列中选择 jsonl 数据列,但即使键存在,也会得到 KeyError

问题描述

这是我在 jsonl 中的数据结构

    db.collection('Goals').doc('Aqd8aP8uLSvuAgsMs5aW').update({"nested": ['12','14']})

我尝试使用此代码从地点列中选择国家/地区代码

"content": "Not yall gassing up a gay boy with no rhythm","place": {"_type": "snscrape.modules.twitter.Place","fullName": "Manhattan,NY","name": "Manhattan","type": "city","country": "United States","countryCode": "US"}

但它给了我这个错误

密钥错误:'国家代码'

我该如何解决这个问题?

我试过这个 method 但它不适合我的情况

解决方法

您可以使用 str 访问它:

country_df['place'].str['countryCode']

输出:

0    US
Name: place,dtype: object
,

因为“地方”基本上是一个 dict(一个嵌套的字典),你可以像访问更高级别的 dict

country = {"content": "Not yall gassing up a gay boy with no rhythm","place": {"_type": "snscrape.modules.twitter.Place","fullName": "Manhattan,NY","name": "Manhattan","type": "city","country": "United States","countryCode": "US"}}
country["place"]["countryCode"]

输出:

'US'

但是,使用 pandas json_normalize() 可能更适合您的目的:

country_df = pd.json_normalize(data = country)

print(country_df )

输出:

内容 place._type place.fullName place.name place.type place.country place.countryCode
不要让一个没有节奏的同性恋男孩气喘吁吁 snscrape.modules.twitter.Place 纽约曼哈顿 曼哈顿 城市 美国 美国