【发布时间】:2022-06-20 06:46:30
【问题描述】:
我有一个非常简单的代码,由于某种原因,当我选择第二列到最后一列时,它会返回一个关键错误。但由于某种原因,第一个按预期工作。
import csv
import pandas as pd
import sys
#terminal parameter:
csv_data = sys.argv[1]
df = pd.read_csv(csv_data)
print(df)
print("\n")
col_heading = str(input("Enter Column Heading: "))
value = str(input("Enter Lookup Value: "))
print(df.loc[df[col_heading] == value])
CSV 如下所示:
Last name, First name, SSN, Test1, Test2, Test3, Test4, Final, Grade
Alfalfa, Aloysius, 123-45-6789, 40.0, 90.0, 100.0, 83.0, 49.0, D-
Alfred, University, 123-12-1234, 41.0, 97.0, 96.0, 97.0, 48.0, D+
Gerty, Gramma, 567-89-0123, 41.0, 80.0, 60.0, 40.0, 44.0, C
Android, Electric, 087-65-4321, 42.0, 23.0, 36.0, 45.0, 47.0, B-
Bumpkin, Fred, 456-78-9012, 43.0, 78.0, 88.0, 77.0, 45.0, A-
Rubble, Betty, 234-56-7890, 44.0, 90.0, 80.0, 90.0, 46.0, C-
Noshow, Cecil, 345-67-8901, 45.0, 11.0, -1.0, 4.0, 43.0, F
Buff, Bif, 632-79-9939, 46.0, 20.0, 30.0, 40.0, 50.0, B+
Airpump, Andrew, 223-45-6789, 49.0 1.0, 90.0, 100.0, 83.0, A
Backus, Jim, 143-12-1234, 48.0, 1.0, 97.0, 96.0, 97.0, A+
Carnivore, Art, 565-89-0123, 44.0, 1.0, 80.0, 60.0, 40.0, D+
Dandy, Jim, 087-75-4321, 47.0, 1.0, 23.0, 36.0, 45.0, C+
Elephant, Ima, 456-71-9012, 45.0, 1.0, 78.0, 88.0, 77.0, B-
Franklin, Benny, 234-56-2890, 50.0, 1.0, 90.0, 80.0, 90.0, B-
George, Boy, 345-67-3901, 40.0, 1.0, 11.0, -1.0, 4.0, B
Heffalump, Harvey, 632-79-9439, 30.0, 1.0, 20.0, 30.0, 40.0, C
这是我收到的错误消息:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3621, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 163, 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: 'First name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\krbss\Documents\PlanIT Testing Automation Testing\Challenge 7.py", line 18, in <module>
print(df.loc[df[col_heading] == value])
File "C:\Python310\lib\site-packages\pandas\core\frame.py", line 3505, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Python310\lib\site-packages\pandas\core\indexes\base.py", line 3623, in get_loc
raise KeyError(key) from err
KeyError: 'First name'
我们将不胜感激。
【问题讨论】:
-
这里很难说,因为数据是表格的,但请确保 CSV 文件中分隔列名的逗号后没有空格。即,确保正确的列名不是带有前导空格的“名字”。
标签: python python-3.x pandas dataframe pandas-loc