我试图将一些数据分离到元数据部分和实际测量中。每个文件都有多个测量值。
.json 文件是这样的。
{
"version": "1",
"data": [
{ ##This starts the first point
"metadata1": 1.1, ##metadata parts
"metadata2": 2.1, #
"metadata3": 3.1, #
"metadata4": 4.1, #
"metadata5": 5.5, #
"measurements": [ ##This is the part that I can't get out
{ #
"datax": 0, #This is the first x-value of the first measurement
"datay": 10 #This is the first y-value of the first measurement
},
{
"datax": .3, #This is the second x-value of the first measurement
"datay": 15 #This is the second y-value of the first measurement
},
{
"datax": .7,
"datay": 25
},
{
"datax": 1.1,
"datay": 40
},
{
"datax": 1.7,
"datay": 55
},
]
},
{ ##This starts the second point
"metadata1": 1.2, ##metadata parts
"metadata2": 2.2, #
"metadata3": 3.2, #
"metadata4": 4.4, #
"metadata5": 5.5, #
"measurements": [ ##This is the part that I can't get out
{ #
"datax": 1, #This is the first x-value of the second measurement
"datay": 20 #This is the first y-value of the second measurement
},
{
"datax": 2.3,
"datay": 35
},
{
"datax": 3.7,
"datay": 25
},
{
"datax": 4.1,
"datay": 30
},
{
"datax": 5.7,
"datay": 32
},
]
}
]
}
我可以轻松获取元数据,但只有第一个测量 x 和 y 值被抓取并卡在同一个槽中。任何从测量中获取数据的尝试都会导致错误。我认为最大的问题是所有 x 和 y 值都标记为相同,这使一切都失败了。我想将所有第一个测量值 datax 和 datay 分组到列表中,将第二个测量值 datax 和 datay 分组到列表中。
with open('Filename.json') as f:
data = json.load(f)
df=pd.DataFrame(data['data'])
display(df)
元数据1 | 元数据2 | 元数据3 | 元数据4 | 元数据5 | 测量 |
---|---|---|---|---|---|
1.1 | 2.1 | 3.1 | 4.1 | 5.1 | [{'datax': 0, 'datay': 10}] |
1.2 | 2.2 | 3.2 | 4.2 | 5.2 | [{'datax': 1, 'datay': 20}] |
我尝试以类似的方式读取文件测量值,但它只给出 KeyError: 'measurements'
with open('Filename.json') as a:
measurements = json.load(a)
df1=pd.DataFrame(data['measurements'])
我想要的是将当前正在工作的元数据的每个方面的所有元数据放入一个列表中。 我现在需要的是将数据分成:
元数据将始终位于每个文件中的同一位置,但测量部分可以是可变长度。
我对此还很陌生,之前从未使用过 json 文件,所以如果这是一个简单的解决方案,请原谅我。如果我没有解释清楚,也请随时提问。
IIUC 你可以做:
for d in data["data"]:
for i, dct in enumerate(d.pop("measurements"), 1):
d[f"point_{i}_x"] = dct["datax"]
d[f"point_{i}_y"] = dct["datay"]
df = pd.DataFrame(data["data"])
print(df)
打印:
metadata1 metadata2 metadata3 metadata4 metadata5 point_1_x point_1_y point_2_x point_2_y point_3_x point_3_y point_4_x point_4_y point_5_x point_5_y
0 1.1 2.1 3.1 4.1 5.5 0 10 0.3 15 0.7 25 1.1 40 1.7 55
1 1.2 2.2 3.2 4.4 5.5 1 20 2.3 35 3.7 25 4.1 30 5.7 32