Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

python - KeyError: 'column_name'

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:UsersDesktopdata.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Asumming 'C:UsersDesktopdata.csv' contains the following data

Distance_Feature Speeding_Feature
1   2
3   4
5   6
 ...

Change

df = pd.read_csv(r'C:UsersDesktopdata.csv')

to

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...