Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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_normalize函数规范化元数据_Python_Json_Pandas - Fatal编程技术网

Python 如何使用json_normalize函数规范化元数据

Python 如何使用json_normalize函数规范化元数据,python,json,pandas,Python,Json,Pandas,我有一个嵌套的json,并希望使用json_normalize函数将其转换为熊猫数据帧 JSON json_input = [{'measurements': [{'value': 111, 'timestamp': 1}, {'value': 222, 'timestamp': 2}], 'sensor': {'name': 'testsensor',

我有一个嵌套的json,并希望使用json_normalize函数将其转换为熊猫数据帧

JSON

json_input = [{'measurements': [{'value': 111, 'timestamp': 1},
                                {'value': 222, 'timestamp': 2}],
               'sensor': {'name': 'testsensor',
                          'id': 1}},
              {'measurements': [{'value': 333, 'timestamp': 1},
                                {'value': 444, 'timestamp': 2}],
               'sensor': None},
              ]
正常化

df = pd.json_normalize(json_input, record_path=['measurements'],
                                   meta=['sensor'])
元数据在上述代码的输出中未得到规范化:

|   | value | timestamp | sensor                          |
|---|-------|-----------|---------------------------------|
| 0 | 111   | 1         | {'name': 'testsensor', 'id': 1} |
| 1 | 222   | 2         | {'name': 'testsensor', 'id': 1} |
| 2 | 111   | 1         | None                            |
| 3 | 222   | 2         | None                            |
是否有可能获得所需的输出:

|   | value | timestamp | sensor.name  | sensor.id |
|---|-------|-----------|--------------|-----------|
| 0 | 111   | 1         | 'testsensor' | 1         |
| 1 | 222   | 2         | 'testsensor' | 1         |
| 2 | 111   | 1         | None         | None      |
| 3 | 222   | 2         | None         | None      |

这将执行->
df['sensor']。应用(pd.Series)。添加前缀(“sensor”)]



正如耶斯雷尔所提到的
.apply(pd.series)
速度较慢您可以使用以下方法:

pd.DataFrame([i if i!=None else {} for i in df['sensor'].tolist()]


通过构造函数创建
DataFrame
,将空列表替换为空dict,并通过以下方式连接在一起:


我认为应该避免使用
apply(pd.Series)
,因为太慢了,谢谢@Pygirl的回答!我测试了它,它对我来说很好。谢谢你的回答!很好。我会评估一下你对@Pygirls answer的评论,这不是主要要求。但我会查出来的@elyptikus-超级,让我知道。@jezrael:这在我的情况下不起作用。它给出:
AttributeError:'NoneType'对象没有属性“键”
,因为也没有值。我正在使用熊猫1.0.3它应该是
如果x==None
那么它对我来说很好。
    value   timestamp   sensor.name sensor.id
0   111     1           testsensor  1.0
1   222     2           testsensor  1.0
2   333     1           NaN         NaN
3   444     2           NaN         NaN
pd.DataFrame([i if i!=None else {} for i in df['sensor'].tolist()]
df = pd.json_normalize(json_input, record_path=['measurements'],
                                   meta=['sensor'])
df = pd.concat([df, pd.DataFrame([i if i!=None else {} for i in df['sensor'].tolist()]
).add_prefix("sensor")], axis=1)
df.drop('sensor', inplace=True, axis=1)
df
df = pd.json_normalize(json_input, record_path=['measurements'],
                                   meta=['sensor'])

#pandas 1.0.1
df1 = pd.DataFrame([{} if x == [] else x for x in df.pop('sensor')]).add_prefix("sensor.")
#pandas 1.0.3
df1 = pd.DataFrame([{} if x == None else x for x in df.pop('sensor')]).add_prefix("sensor.")

df = pd.concat([df, df1], axis=1)
print (df)
   value  timestamp sensor.name  sensor.id
0    111          1  testsensor        1.0
1    222          2  testsensor        1.0
2    333          1         NaN        NaN
3    444          2         NaN        NaN