正在获取已存在的pandas-df列名的KeyError



我有

data_combined = pd.read_csv("/path/to/creole_data/data_combined.csv", sep=";", encoding='cp1252')

所以,当我尝试访问这些行时:

data_combined = data_combined[(data_combined["wals_code"]=="abk") &(data_combined["wals_code"]=="aco")]

我得到一个KeyError"wals_code"。然后我用检查了我的colname列表

print(data_combined.columns.tolist())

并在列表中看到了colname"wals_code"。这是打印出来的前几项。

[',"wals_code","Order of subject, object and verb","Order of genitive and noun","Order of adjective and noun","Order of adposition and NP","Order of demonstrative and noun","Order of numeral and noun","Order of RC and noun","Order of degree word and adjective"]

有人知道我的文件出了什么问题吗?

问题在于读取CSV文件时使用的分隔符。使用sep=';',可以指示read_csv使用分号(;(作为列(单元格列标题(的分隔符,但从列打印输出中可以看出,CSV文件实际上使用了逗号(,(。

如果您仔细查看,您会注意到您的列打印输出实际上显示了一个包含一个长字符串的列表,而不是表示列名的单个字符串的列表。

因此,使用sep=','而不是sep=';'(或者完全省略它,因为,sep的默认值(:

data_combined = pd.read_csv("/path/to/creole_data/data_combined.csv", encoding='cp1252')

最新更新