繁体   English   中英

如何将传感器数据列表(.txt)的拆分结果输入到变量中

[英]How to input the results of the split from the list of sensor data (.txt) into a variable

如何将传感器数据列表(.txt)的拆分结果输入到python 3中的变量中?

例如 :

我有数据.txt:

0000003623,-0.028333g, 0.005556g, 0.996296g, 22.978836deg
0000003624, 0.028704g, 0.004815g, 0.996296g, 22.978836deg

我需要 :

col_0 = 0000003623, 0000003624
col_1 = -0.028333g, 0.028704g
...
col_5 = col_0*col_1

并将col_5的结果插入/附加到文件.txt中,例如:

0000003623,-0.028333g, 0.005556g, 0.996296g, 22.978836deg, col_5
0000003624, 0.028704g, 0.004815g, 0.996296g, 22.978836deg, col_5

那是什么代码?

我之前尝试过使用此数据。 txt值为:

0000003623,-0.028333g, 0.005556g, 0.996296g, 22.978836deg
0000003624, 0.028704g, 0.004815g, 0.996296g, 22.978836deg
0000003625,-0.028704g, 0.004444g, 0.996111g, 22.925926deg
0000003626, 0.029444g, 0.003704g, 0.995741g, 22.978836deg
0000003627,-0.030000g, 0.003889g, 0.996296g, 22.978836deg

当我使用代码时:

file = open("C:\\Users\\{name_computer}\\zzBelajarPys\\CobaSensor3.txt", "r")
for line in file:
    x=line.split(',')
    print(x[0])

file.close()

copile的结果是:

0000003623
0000003624
0000003625
0000003626
0000003627

但是当我使用代码时:

file = open("C:\\Users\\{name_computer}\\zzBelajarPys\\CobaSensor3.txt", "r")
for line in file:
    x=line.split(',')
    print(x[0],x[1])

file.close()

copile的结果是:

0000003623 -0.028333g
Traceback (most recent call last):
  File "C:/Users/{name_computer}/zzBelajarPys/bacatxtp8_2.py", line 4, in <module>
    print(x[0],x[1])
IndexError: list index out of range

通过查看data.txt内容,您可以观察到实际上是.csv格式,因此我将使用熊猫(我一直在使用python 3.6的jupyter笔记本,但是您可以在具有python 3的任何地方使用该代码):

import pandas as pd

df = pd.read_csv('data.txt', names=['col_0', 'col_1', 'col_2', 'col_3', 'col_4'])
df

输出:

在此处输入图片说明

df.col_0.values.tolist()
# output : [3623, 3624, 3625, 3626, 3627]

df.col_1.values.tolist()
# output : ['-0.028333g', ' 0.028704g', '-0.028704g', ' 0.029444g', '-0.030000g']

# we need to cast to float in order to be able to get col_5
df.col_1 = df.col_1.apply(lambda x: float(x.replace('g', '')))
df

输出:

在此处输入图片说明

df['col_5'] = df.col_0 * df.col_1
df

输出:

在此处输入图片说明

您只需要保存df:

df.to_csv('data.txt',  header=False, index=False)

如果您不希望修改col_1,则只需将col_1的内容保存在变量中(开头),然后再保存最终数据之前,可以将col_1更改回其原始数据

暂无
暂无

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

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