KeyError:"column_name" [英] KeyError: 'column_name'

查看:402
本文介绍了KeyError:"column_name"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个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:\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.

推荐答案

假设'C:\ Users \ Desktop \ data.csv'包含以下数据

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

Distance_Feature Speeding_Feature
1   2
3   4
5   6
 ...

更改

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

    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`.

这篇关于KeyError:"column_name"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆