【问题标题】:Is there a way to un-nesting a pandas dataframe in a python3 jupyter notebook?有没有办法在 python3 jupyter 笔记本中取消嵌套熊猫数据框?
【发布时间】:2019-07-16 19:17:08
【问题描述】:

我正在将 json 文件导入 python3 jupyter notebook。 json文件格式为

  1. 对象
    • 房间[26个元素]
      • 0
        • 转
          • 来自浴室
          • 从停车场
        • 距离
          • dfromBathroom
          • dfromParking
        • 深度
        • 地区
      • 1
        • ....等
    • 姓名

我是这样导入json文件的:

import pandas as pd
import numpy as np
import json
from pandas.io.json import json_normalize

with open("rooms.json") as file:
  data = json.load(file)
df = json_normalize(data['rooms'])

我现在尝试以类似矩阵的格式绘制 6 个维度中的每一个,总共 36 个图。

我正在尝试以下方式:

col_features = ['fromBathroom', 'fromParking', 'dfromBathroom', 'dfromParking', 'depth', 'area']
pd.plotting.scatter_matrix(df[col_features], alpha = .2, figsize = (14,8))

这不起作用,因为我收到一条错误消息: KeyError:“['fromBathroom' 'fromParking' 'dfromBathroom' 'dfromParking'] 不在索引中”

这是因为这些特征嵌套在 json 文件中的“转弯”和“距离”中。有没有办法取消嵌套这些特征,以便我可以像获取深度和面积一样索引到数据框以获取值?

感谢您提供任何见解。

【问题讨论】:

    标签: python pandas dataframe jupyter-notebook dimensionality-reduction


    【解决方案1】:

    也许你可以提取df1 = df['turns']、df2 = df['distances']和df3 = df['areas', 'depth]然后做一个df4 = pd.concat([df1, df2, df3], join='inner', axis=1)see pandas doc

    或直接:pd.concat([df['turns'], df['distances'], df['areas', 'depth]], join='inner', axis=1)

    编辑:

    我尝试了一些东西,我希望它是你想要的:

    link to the image with the code and the results I get with Jupyter

    df1 = df['turns']
    df2 = df['distances']
    df3 = pd.DataFrame(df['depth'])
    df4 = pd.DataFrame(df['area'])
    df_recomposed = pd.concat([df1, df2, df3, df4], join='inner', axis=1)
    

    或Pandas - How to flatten a hierarchical index in columns

    df.columns = [' '.join(col).strip() for col in df.columns.values] 应该是您要查找的内容

    【讨论】:

    • 这是个好主意!现在尝试这样做,除非我用“转弯”和“距离”索引数据框,否则我会得到一个 KeyError。当我说print(df['area']) 时,我得到了一个具有正确值的系列对象。不知道为什么一个有效而另一个无效:(
    • 尝试将每个系列转换为数据框:See this stackoverflow thread
    猜你喜欢
    • 2017-03-26
    • 2021-12-03
    • 2022-01-06
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2018-04-27
    相关资源
    最近更新 更多