繁体   English   中英

将格式为字典的 csv 文件读入 pandas

[英]Reading csv file formatted as dictioary into pandas

我有一个包含传感器数据的 csv 文件,其中一行的格式如下

1616580317.0733, {'Roll': 0.563820598084682, 'Pitch': 0.29817540218781163, 'Yaw': 60.18415650363684, 'gyroX': 0.006687641609460116, 'gyroY': -0.012394784949719908, 'gyroZ': -0.0027120113372802734, 'accX': -0.12778355181217196, 'accY': 0.24647256731987, 'accZ': 9.763526916503906}

其中第一列是时间戳,其余列是像 object 这样的字典,其中包含各种测量量。

我想将其读入 pandas 数组,其中包含["Timestamp","Roll","Pitch","Yaw","gyroX","gyroY","gyroZ","accX","accY","accZ"] 这样做的有效方法是什么? 该文件为 600MB,因此需要解析的行数并不多。

我不确定你从哪里得到秒列。

下面的代码将每一行解析为时间戳和字典。 然后将时间戳添加到字典中,最终将成为 dataframe 中的一行。

import json
import pandas as pd


def read_file(filename):
    

    chunk_size = 20000
    entries = []
    counter = 0
    
    df = pd.DataFrame()

    with open(filename, "r") as fh:
        for line in fh:
            timestamp, data_dict = line.split(",", 1)
            data_dict = json.loads(data_dict.replace("'", '"'))
            data_dict["timestamp"] = float(timestamp)
            entries.append(data_dict)
            counter += 1
            
            if counter == chunk_size:
                df = df.append(entries, ignore_index=True)
                entries = []
                counter = 0
                
        if counter != 0:
            df = df.append(entries, ignore_index=True)

                
    return df

read_file("sample.txt")

I think you should convert your csv file to json format and then look at this site on how to transform the dictionary into a pandas dataframe: https://www.delftstack.com/fr/howto/python-pandas/how-to-将python-dictionary-to-pandas-dataframe/#:~:text=2%20banana%2012-,M%C3%A9thode%20pandas.,le%20nom%20de%20la%20colonne

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM