首頁 > 後端開發 > Python教學 > 為什麼在存取 Pandas DataFrame 中的欄位時出現 KeyError?

為什麼在存取 Pandas DataFrame 中的欄位時出現 KeyError?

Patricia Arquette
發布: 2024-11-15 12:07:02
原創
984 人瀏覽過

Why Am I Getting a KeyError When Accessing Columns in My Pandas DataFrame?

Error: pandas HashTable KeyError

When attempting to print a specific column from a pandas DataFrame, you may encounter a KeyError if the requested column name does not exist in the DataFrame. This issue can arise due to several reasons, including hidden whitespace in column names or incorrect separator settings during CSV reading.

To investigate the issue further, first check the actual column names by printing the DataFrame's columns as a list:

print(reviews_new.columns.tolist())
登入後複製

Possible solutions include:

Whitespaces in Column Names:

  • Strip whitespace from column names using reviews_new.columns = reviews_new.columns.str.strip().
  • Alternatively, pass skipinitialspace=True to read_csv.

Incorrect Separator:

  • Check the CSV file separator and pass the correct separator using sep parameter in read_csv. For example:
reviews_new = pd.read_csv("D:\\aviva.csv", sep=';')  # Semicolon separator
reviews_new = pd.read_csv("D:\\aviva.csv", sep='\s+')  # Whitespace separator
登入後複製

Absence of Column Name:

If the DataFrame does not have a column with the specified name, the error persists. To resolve this, select the first column by accessing the DataFrame's .index attribute. For example:

print(reviews_new.index.get_level_values('col1'))  # For MultiIndex
登入後複製

By following these steps, you can identify and resolve the cause of the KeyError and correctly access the desired column in your DataFrame.

以上是為什麼在存取 Pandas DataFrame 中的欄位時出現 KeyError?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板