Pandas无法访问非索引列

时间:2017-11-14 05:09:03

标签: python pandas

我尝试使用Kaggle的数据创建一个流失模型。当我尝试做一个train_test_split时,我得到一个KeyError:" [' temin' ' tdchar']不在索引"有谁知道我是否真的需要索引列来访问数据? 以下是我的代码:

import pandas as pd
from sklearn.cross_validation import train_test_split
df_churn = pd.read_csv("https://storage.googleapis.com/kaggle-competitions-data/kaggle/6716/churn_train.txt?GoogleAccessId=competitions-data@kaggle-161607.iam.gserviceaccount.com&Expires=1510894749&Signature=TjX%2ByvtIpVtVls5YK48iS%2Fpu4ajHGARwNsLNVz5SVEO8SBz9SPZVkdR0vHj4nRbJY3LxDHXXP3jsRdIoljaExRy1oZ%2Fadk2q08besx8RZdHlhv7wEd1r6Djqe9ybfMusgL42%2BQvEg4FuIKf3Ayzuxz%2BXaN1rIZZkRMgcj7XFpL3ao6ITgI3XjfM%2FrYs5CIGS2r75Az6YWe5PjFhzjGb23ndYo%2Ftzh02QcDwZ6122f3sAwY045tWcY4NZNOA7EiAt7l12wifiI1NytB5Q2cid9YFUhIx5mSVOqXaXr6NCbj62VpVTq9Ic76w5UT9tu%2FsFjTS7WN5hQY625IT3yAxoFg%3D%3D")

X_train, y_train, X_test, y_test = train_test_split(df_churn[["temin","tdchar"]],df_churn[["label"]],test_size=.3)

我收到以下错误消息:

KeyError: "['temin' 'tdchar'] not in index"

1 个答案:

答案 0 :(得分:2)

您的列名称中包含空格:

df_churn.columns

Index(['st', ' acclen', ' arcode', ' phnum', ' intplan', ' voice',
       'nummailmes', ' tdmin', ' tdcal', ' tdchar', ' temin', ' tecal',
       ' tecahr', ' tnmin', ' tn cal', ' tnchar', ' timin', ' tical',
       ' tichar ncsc', ' label'],
      dtype='object')

所以,剥去他们:

df_churn.columns = df_churn.columns.str.strip()

现在可以使用了!

X = df_churn[["temin", "tdchar"]]
y = df_churn[["label"]]
X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=.3)