栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在熊猫数据框中展平嵌套的Json

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在熊猫数据框中展平嵌套的Json

如果您正在寻找一种更通用的方法来从json展开多个层次结构,则可以使用

recursion
并列出理解来重塑数据。下面介绍了一种替代方法:

def flatten_json(nested_json, exclude=['']):    """Flatten json object with nested keys into a single level.        Args: nested_json: A nested json object. exclude: Keys to exclude from output.        Returns: The flattened json object if successful, None otherwise.    """    out = {}    def flatten(x, name='', exclude=exclude):        if type(x) is dict: for a in x:     if a not in exclude: flatten(x[a], name + a + '_')        elif type(x) is list: i = 0 for a in x:     flatten(a, name + str(i) + '_')     i += 1        else: out[name[:-1]] = x    flatten(nested_json)    return out

然后,您可以独立于嵌套级别将其应用于数据:

新样本数据

this_dict = {'events': [  {'id': 142896214,   'playerId': 37831,   'teamId': 3157,   'matchId': 2214569,   'matchPeriod': '1H',   'eventSec': 0.8935539999999946,   'eventId': 8,   'eventName': 'Pass',   'subEventId': 85,   'subEventName': 'Simple pass',   'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53}],   'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]}, {'id': 142896214,   'playerId': 37831,   'teamId': 3157,   'matchId': 2214569,   'matchPeriod': '1H',   'eventSec': 0.8935539999999946,   'eventId': 8,   'eventName': 'Pass',   'subEventId': 85,   'subEventName': 'Simple pass',   'positions': [{'x': 51, 'y': 49}, {'x': 40, 'y': 53},{'x': 51, 'y': 49}],   'tags': [{'id': 1801, 'tag': {'label': 'accurate'}}]}]}

用法

pd.Dataframe([flatten_json(x) for x in this_dict['events']])Out[1]:          id  playerId  teamId  matchId matchPeriod  eventSec  eventId    142896214     37831    3157  2214569          1H  0.893554        8   1  142896214     37831    3157  2214569          1H  0.893554        8  eventName  subEventId subEventName  positions_0_x  positions_0_y        Pass          85  Simple pass  51  49   1      Pass          85  Simple pass  51  49   positions_1_x  positions_1_y  tags_0_id tags_0_tag_label  positions_2_x    40  53       1801         accurate NaN   1  40  53       1801         accurate51.0   positions_2_y  0 NaN  149.0

请注意,该

flatten_json
代码不是我的代码,我在这里和这里都看到了它,而对原始源代码的不确定性很高。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/391221.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号