【问题标题】:Read data from a map object within JSON into a Pandas Dataframe从 JSON 中的地图对象读取数据到 Pandas Dataframe
【发布时间】:2020-10-18 22:39:21
【问题描述】:

我正在尝试将 JSON 文件中的数据访问到 pandas 数据帧中,并且似乎被困在如何检索 JSON 映射中的数据。

我想将此json的用户对象中的followers_count实体检索到数据框中。

JSON 文件(示例记录)如下:

{"created_at": "Tue Aug 01 16:23:56 +0000 2017", "id": 892420643555336193, "retweet_count": 12345, "favorite_count": 23456, "user": {"id": 4196983835, "followers_count": 3200889, "friends_count": 104}}

这是我在代码方面的内容(不起作用,因为我不知道如何获取用户对象中的 follower_count :

        tweet_data_df = pd.read_json('tweet-json.txt', lines=True)
        #Doesnt work
        #tweet_data_df = tweet_data_df[['id', 'favorite_count', 'retweet_count', 'created_at', 'user''followers_count']]
        #works but not enough for me
        tweet_data_df = tweet_data_df[['id', 'favorite_count', 'retweet_count', 'created_at']]
        tweet_data_df.head(5)

感谢您的帮助!

【问题讨论】:

  • 如果 json 字典的 depth = 2 你可以使用pd.DataFrame(json_dict).apply(pd.Series) ?

标签: python json pandas dataframe


【解决方案1】:

如果 json 对象 (dictionary) 有一个 depth = 2,(即只有 2 个嵌套字典),您可以使用 .apply(pd.Series)

{"key": {"key2":{val1, val2}} # depth = 2
{"key": {"key2":{val1, "key3":{val2}} # depth > 2, depth = 3

pd.DataFrame(dic).apply(pd.Series).reset_index(drop = True)

否则depth > 2 你可以遍历它的键递归

def shrink_depth(dic, output_dict: dict, pkey= None):
    if isinstance(dic, dict):
        for key in dic:
            if key not in output_dict.keys():
                output_dict[key] = []
            
            shrink_depth(dic[key], output_dict, key) # call
    
    elif isinstance(dic, (list, set)):
        for val in dic:
            output_dict[pkey].append(val)
    else:
        output_dict[pkey].append(dic)

# update: Add nested dictionaries to the (id) key
dic = {"created_at": "Tue Aug 01 16:23:56 +0000 2017", "id": 892420643555336193, "retweet_count": 12345, "favorite_count": 23456, 
               "user": {"id": {4196983835: 43424}, "followers_count": 3200889, "friends_count": 104}}

output = {}

shrink_depth(dic, output)

output

{'created_at': ['Tue Aug 01 16:23:56 +0000 2017'],
 'id': [892420643555336193],
 'retweet_count': [12345],
 'favorite_count': [23456],
 'user': [],
 4196983835: [43424],
 'followers_count': [3200889],
 'friends_count': [104]}

【讨论】:

  • 只是为了理解 - 您是否建议修改 JSON 对象以适应这一点?
  • 是的,将json转换为字典,然后缩小其深度,但在你的情况下,你可以直接使用第一个
  • 抱歉,我无法将带有 JSON 数据的 txt 文件转换为字典。尝试了一些代码,但会引发错误。
  • 试过这个:用 open('tweet-json.txt', 'r') as json_file: json_dict = json.load(json_file)
  • JSONDecodeError: Extra data: line 2 column 1 (char 3974) - 它是来自第三方站点的有效 json 文件
猜你喜欢
  • 2020-11-26
  • 2018-01-23
  • 2013-07-16
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
  • 2019-04-22
  • 2021-11-14
  • 1970-01-01
相关资源
最近更新 更多