text_plain_output_1.png
from sklearn import preprocessing,cross_validation,neighbors

import numpy as np # linear algebra

import pandas as pd

import numpy as np
import pandas as pd
from sklearn import preprocessing, cross_validation, neighbors
def handle_non_numeric(df):
    columns = df.columns.values
    for col in columns:
        text_digit_vals = {}
        def convert_to_int(val):
            return text_digit_vals[val]
        if df[col].dtype != np.int64 and df[col].dtype != np.float64:
            column_contents = df[col].values.tolist()
            unique_elements = set(column_contents)
            x = 0
            for unique in unique_elements:
                if unique not in text_digit_vals:
                    text_digit_vals[unique] = x
                    x += 1
            df[col] = list(map(convert_to_int, df[col]))
    return df
df_o = pd.read_csv('../input/Family Income and Expenditure.csv')

quants = list(df_o['Total Household Income'].quantile([0.25, 0.5, 0.75]))
print('quantiles', quants)
income_cat = []
for i in df_o['Total Household Income']:
    if i < quants[0]:
        income_cat.append('P')
    elif i >= quants[0] and i < quants[1]:
        income_cat.append('LM')
    elif i >= quants[1] and i < quants[2]:
        income_cat.append('HM')
    else:
        income_cat.append('R')
df = df_o.drop('Total Household Income', 1)
df['Income'] = income_cat
df = handle_non_numeric(df)
X = np.array(df.drop('Income', 1).astype(float))
X = preprocessing.scale(X)
y = np.array(df['Income'])
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)
clf = neighbors.KNeighborsClassifier()
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)
print('accuracy', accuracy)