如何使用python将CSV文件中的原始传感器数据分组

时间:2018-07-12 15:10:40

标签: python grouping tabular

我通过以下代码从移动设备(加速度计,陀螺仪和磁场)获取三种类型的传感器数据(这很糟糕,因为我只是从python开始,但是无论如何它们都可以工作:))。

# maybe barometre2013 has missing column names missing.column.names <- setdiff(names(baro1618), names(barometre2013)) barometre2013[, missing.column.names] <- NA # maybe baro1618 has missing column names missing.column.names <- setdiff(names(barometre2013), names(baro1618)) baro1618[, missing.column.names] <- NA

import socket, traceback
host = ''
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))

#used for debugging
count=0
print("Success binding")
while count<10:
    message, address = s.recvfrom(5555)
    messageString = message.decode("utf-8")
    print(messageString)
    count=count+1
    with open('yourfile.csv','a') as f:
     f.write(messageString)
     f.close()

但是我在csv文件中得到的输出是这样的- import socket, traceback host = '' port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) #used for debugging count=0 print("Success binding") while count<10: message, address = s.recvfrom(5555) messageString = message.decode("utf-8") print(messageString) count=count+1 with open('yourfile.csv','a') as f: f.write(messageString) f.close()

第一个大数字是时间戳记,3,4,5是传感器ID,后跟它们的x,y,z坐标值。 现在,需要针对每个时间戳将原始数据按其传感器ID以表格格式进行分组。如果不需要复杂的编码,那么有意义的列标题将非常有用。我正在尝试在下面提供示例-

Expected output

我从Github安装了veryprettytable,但是代码或实现超出了我的python知识。 请帮忙。 我正在Windows 10上使用最新的python 3.27(2018年6月)。

2 个答案:

答案 0 :(得分:0)

在这种情况下应该可以使用:

while count<10:
    message, address = s.recvfrom(5555)
    messageString = message.decode("utf-8")
    print(messageString)
    count=count+1
    filename = yourfile.xlsx

    workbook = Workbook(filename + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(filename , 'rt', encoding='utf8') as f:

        for r, row in enumerate(reader):
        print(r)
        for c, col in enumerate(messageString):
            worksheet.write(r, c, col)
    workbook.close()

答案 1 :(得分:0)

要获得所需的输出,您需要

  • 添加所需的标题信息
  • 剥离掉不需要的空间 messageString
  • 在写之前在换行符上添加换行符

要执行标头信息,您需要类似

fid = open('yourfile.csv', 'w')
fid.write('timestamp,,accelerometer,,gyroscope,,magnetic field\n')
fid.write(',x,y,z,x,y,z,x,y,z\n')
fid.close()

在原始文章中,很难说出messageString是如何生成的。但是很明显,字段之间有空格。您需要以某种方式剥离它们。要将它们从现有的messageString中剥离,请使用str.replace:

messageString = messageString.replace(' ', '') # replace space with empty string

最后,在messageString上添加换行符非常简单:

messageString += '\n'

messageString = messageString + '\n'