Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从JSON中的映射对象将数据读取到数据帧中_Python_Json_Pandas_Dataframe - Fatal编程技术网

Python 从JSON中的映射对象将数据读取到数据帧中

Python 从JSON中的映射对象将数据读取到数据帧中,python,json,pandas,dataframe,Python,Json,Pandas,Dataframe,我试图将JSON文件中的数据访问到pandas数据框架中,似乎被困在如何在JSON映射中检索数据上 我想将这个json的用户对象中的followers\u count实体检索到一个数据帧中 JSON文件(示例记录)如下: 以下是我的代码(不起作用,因为我不知道如何获取用户对象中的followers\u计数): tweet_data_df = pd.read_json('tweet-json.txt', lines=True) #Doesnt work

我试图将JSON文件中的数据访问到pandas数据框架中,似乎被困在如何在JSON映射中检索数据上

我想将这个json的用户对象中的followers\u count实体检索到一个数据帧中

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

以下是我的代码(不起作用,因为我不知道如何获取用户对象中的followers\u计数):

        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对象(
dictionary
)具有
depth=2
,(即只有两个嵌套字典),您可以使用
.apply(pd.Series)


否则
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)



如果json字典的深度为2,则可以使用
pd.DataFrame(json_dict).apply(pd.Series)
?我只是想了解一下-您是否建议修改JSON对象以适应这种情况?是的,将JSON转换为字典,然后缩小其深度,但在您的情况下,您可以直接使用第一个。抱歉,我无法将包含JSON数据的txt文件转换为字典。尝试了一些代码,但会引发错误。尝试了以下操作:使用open('tweet-json.txt','r')作为json_文件:json_dict=json.load(json_文件)JSONDecodeError:额外数据:第2行第1列(char 3974)-但它是来自第三方站点的有效json文件
{"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)
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]}