當我嘗試將 CSV 檔案加載到資料框中然后對其進行資料分析時,我似乎遇到了錯誤。
我在使用列作為資料點創建一個簡單的圖時遇到了麻煩。
df.{column name} 不作業。
編碼:
import pandas as pd
#column_names = ['area', 'bedrooms', 'age', 'price', 'Unnamed']
df = pd.read_csv("testfile.csv")
print(df)
df = df.loc[:, ~df.columns.str.contains('^Unnamed')] # rRemove NAN column
print(df)
print(df.bedrooms.median())
錯誤:
'DataFrame' object has no attribute 'bedrooms'
CSV 檔案:
area, bedrooms, age, price,
2600, 3, 20, 550000,
3000, 4, 15, 565000,
3200, 0, 18, 610000,
3600, 3, 30, 595000,
4000, 5, 8, 760000,
uj5u.com熱心網友回復:
您的列周圍有空格:
>>> df.columns
Index(['area', ' bedrooms', ' age', ' price'], dtype='object')
^ ^ ^
您可以使用.str.strip()(就像使用普通系列一樣)洗掉它:
df.columns = df.columns.str.strip()
輸出:
>>> print(df.bedrooms.median())
3.0
您還可以通過洗掉 CSV 標題中逗號之前/之后的所有空格來更正 CSV 檔案:
area,bedrooms,age,price,
2600, 3, 20, 550000,
3000, 4, 15, 565000,
3200, 0, 18, 610000,
3600, 3, 30, 595000,
4000, 5, 8, 760000,
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362508.html
