【发布时间】:2021-08-11 23:20:46
【问题描述】:
我希望有人可以帮助我解决这个问题。在树莓派上安装 numpy 做噩梦后,我又被卡住了! 我想做的事情的要点是我有一个 arduino,它通过 lora 将数字(手动输入的围兜号码)发送到树莓派的 rx。 该脚本应该读取传入的数据, - 它会打印出来,以便我可以在终端中看到它。然后 Pandas 应该将该数字与 txt/csv 文件进行比较,如果它在 bib number 列中匹配,则应该将匹配的行附加到一个新文件中。 现在,第一位工作(捕获数据和打印),在我的 Windows PC 上,当我使用固定数字而不是传入数据进行测试时,第二位工作。 我基本上已经尽我所能将它们混合在一起以获取传入的数字来进行比较。
我还应该说明错误发生在我在 arduino 上按 3 之后(然后在出错之前打印在树莓派的终端上),所以可能是 keyerror 3
我的代码在这里
#!/usr/bin/env python3
import serial
import csv
import pandas as pd
#import numpy as np
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyS0', 9600, timeout=1)
ser.flush()
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
print(line)
with open ("test_data.csv","a") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow([line])
df = pd.read_csv("data.txt")
#out = (line)
filtered_df = df[line]
print('Original Dataframe\n---------------\n',df)
print('\nFiltered Dataframe\n------------------\n',filtered_df)
filtered_df.to_csv("data_amended.txt", mode='a', index=False, header=False)
#print(df.to_string())
我的错误在这里:
Python 3.7.3 (/usr/bin/python3)
>>> %Run piserialmashupv1.py
3
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas/_libs/index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: '3'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/pi/piserialmashupv1.py", line 20, in <module>
filtered_df = df[line]
File "/home/pi/.local/lib/python3.7/site-packages/pandas/core/frame.py", line 3455, in __getitem__
indexer = self.columns.get_loc(key)
File "/home/pi/.local/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3363, in get_loc
raise KeyError(key) from err
KeyError: '3'
>>>
我被要求输入 data.txt
的前几行_id,firstname,surname,team,info
1, Peter,Smith,,Red Walk (70 miles- 14 mile walk/run + 56 mile cycle)
2, Samantha,Grey,Team Grey,Blue walk (14 mile walk/run)
3, Gary,Parker,,Red Walk (70 miles- 14 mile walk/run + 56 mile cycle)
我认为这一定是我引用传入 rx 号码的方式?
非常感谢任何帮助! 戴夫
【问题讨论】:
-
您能否edit your question 包括您的 data.txt(或类似的示例文件)的前 3 行?
-
谢谢@enzo 我已经添加了data.txt。另外,我想通了(在一点帮助下)固定代码在答案中。新代码运行了,但没有给我任何过滤数据。这是因为我从 RX 读取的数据类型保存为整数,并且在执行 pandas 过滤器时我没有指定,所以它无法正确使用它。您还将看到我添加了:ser.write("Y".encode()) 这是因为我有另一个脚本可以向 arduino 发送 ping 以显示连接,但这会干扰接收,所以我将其添加为响应
标签: python-3.x keyerror