You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将手机加速度计JSON数据解析为DataFrame

嘿,我来帮你把这个加速度计数据转换成你想要的DataFrame!你的数据结构有点嵌套,但拆解起来很简单,用pandas就能轻松搞定。

首先,先理清楚你的数据结构:timestamps是一个字典,键是时间戳字符串,每个键对应的值是一个列表——第一个元素是你要的列名(x、y、z这些),后面的每一个子列表都是一行数值数据。

直接上代码,一步到位:

import pandas as pd

# 你的原始加速度计数据(我把Python2的u前缀去掉了,Python3不需要这个)
accel_data = {
    'timestamps': {
        '1524771017235': [
            ['x', 'y', 'z', 'rotationX', 'rotationY', 'rotationZ'],
            [-0.02, 0, 0.04, 102.65, 68.15, 108.61],
            [-0.03, 0.02, 0.02, 102.63, 68.2, 108.5],
            [-0.05, 0.01, 0.1, 102.6, 68.25, 108.4],
            [-0.02, 0, 0.09, 102.6, 68.25, 108.4],
            [-0.01, 0, 0.03, 102.6, 68.25, 108.4]
        ]
    }
}

# 提取时间戳对应的数据集(这里只有一个时间戳,直接取第一个值)
dataset = next(iter(accel_data['timestamps'].values()))
# 拿到列名(列表的第一个元素)
column_names = dataset[0]
# 拿到所有数值行(从第二个元素开始到末尾)
numeric_rows = dataset[1:]

# 创建目标DataFrame
df = pd.DataFrame(numeric_rows, columns=column_names)

# 打印看看结果
print(df)

运行这段代码后,你会得到一个完美符合需求的DataFrame:列就是x、y、z、rotationX、rotationY、rotationZ,每一行对应一组数值数据。

如果你的timestamps里有多个时间戳(比如多个不同的时间点数据),我也给你准备了扩展方案——可以给每行加上对应的时间戳列,方便后续分析:

all_rows = []
# 遍历所有时间戳和对应的数据
for timestamp, data in accel_data['timestamps'].items():
    cols = data[0]
    rows = data[1:]
    # 给每一行加上当前时间戳
    for row in rows:
        all_rows.append([timestamp] + row)

# 创建带时间戳的DataFrame
df_with_ts = pd.DataFrame(all_rows, columns=['timestamp'] + cols)
print(df_with_ts)

这样处理后,你就能同时看到每组数据对应的时间戳啦!

内容的提问来源于stack exchange,提问作者J_yang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:53:44