熊猫DataFrame KeyError

时间:2018-08-17 21:28:33

标签: python pandas

首先,这是代码:

import pandas as pd

headers = ["Category", "Brand", "Product_Name", "Shipping", "Price"]

xl = pd.ExcelFile("C:\\Users\\*myusername*\\Desktop\\products.xlsx")
df = xl.parse("products")
print(df)

df = df.sort_values(by=headers[4], axis='columns', na_position='last')

writer = pd.ExcelWriter('C:\\Users\\*myusername*\\Desktop\\output.xlsx')
df.to_excel(writer, sheet_name="Sheet1", columns=headers, index=False)
writer.save()

print("Done")

我试图做的是整理一些我从Newegg收集的数据,作为一种练习项目。我打算在这里使用此代码,并将其扩展以对数据进行各种处理,但是我认为我会很容易开始,只需按Price列对它们进行排序。

运行上面的代码时,它将引发以下错误:

  File "<input>", line 9, in <module>
  File "C:\Users\mmiller3\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 4421, in sort_values
    stacklevel=stacklevel)
  File "C:\Users\mmiller3\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\generic.py", line 1382, in _get_label_or_level_values
    raise KeyError(key)
KeyError: 'Price'

当我打印(df)时,从解析的xl表创建它之后,它会正确显示5个标头以及其中包含的所有数据。标头“价格”肯定存在。

print(df)输出如下:

            Category           Brand   ...     Shipping Costs   Price 
0      Desktop Memory         G.SKILL   ...      Free Shipping  199.99 
1      Desktop Memory         G.SKILL   ...      Free Shipping  143.99

那只是输出的一小段,持续了147行。

我尝试了很多事情,包括用更直接的“价格”替换“标头[4]”,我尝试在列中标明“ E”,而不是使用标头。

在这一点上,我很困惑,我发现的关于此特定问题的唯一其他参考文献是一个简单的语法错误,但我没有犯同样的错误。

大家能为我提供的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您应该能够做到

df = xl.parse("products", names = headers)
相关问题