KeyError: 'column_name'

僤鯓⒐⒋嵵緔 提交于 2019-12-13 09:55:14

问题


I am writing a python code, it should read the values of columns but I am getting the KeyError: 'column_name' error. Can anyone please tell me how to fix this issue.

import numpy as np
from sklearn.cluster import KMeans
import pandas as pd


### For the purposes of this example, we store feature data from our
### dataframe `df`, in the `f1` and `f2` arrays. We combine this into
### a feature matrix `X` before entering it into the algorithm.

df = pd.read_csv(r'C:\Users\Desktop\data.csv')

print (df)

#df = pd.read_csv(csv_file)

"""
saved_column = df.Distance_Feature
saved_column = df.Speeding_Feature

print(saved_column)
"""

f1 = df['Distance_Feature'].tolist()
f2 = df['Speeding_Feature'].tolist()

print(f1)
print(f2)

X=np.matrix(zip(f1,f2))

print(X)

kmeans = KMeans(n_clusters=2).fit(X)

Can anyone please help me.


回答1:


Asumming 'C:\Users\Desktop\data.csv' contains the following data

Distance_Feature Speeding_Feature
1   2
3   4
5   6
 ...

Change

df = pd.read_csv(r'C:\Users\Desktop\data.csv')

to

    df = pd.read_csv("data.txt",names=["Distance_Feature","Speeding_Feature"],sep= "\s+|\t+|\s+\t+|\t+\s+",header=1) 
    # Here it is assumed white space separator, if another separator is used change `sep`.


来源:https://stackoverflow.com/questions/48640677/keyerror-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!