numpy loadtxtの非常に優れた代替手段は、Pandasのread_csvです。データはPandasデータフレームに読み込まれ、一部の列にテキストが含まれ、他の列に数値が含まれるなど、混合データ型を処理できるという大きな利点があります。その後、数値列のみを簡単に選択し、as_matrixを使用してnumpy配列に変換できます。パンダはまた、Excelファイルや他の多くの形式の読み取り/書き込みを行います。
「mydata.csv」という名前のcsvファイルがある場合:
point_latitude,point_longitude,line,construction,point_granularity
30.102261, -81.711777, Residential, Masonry, 1
30.063936, -81.707664, Residential, Masonry, 3
30.089579, -81.700455, Residential, Wood , 1
30.063236, -81.707703, Residential, Wood , 3
30.060614, -81.702675, Residential, Wood , 1
これにより、csvが読み込まれ、数値列がscikit_learnのnumpy配列に変換され、列の順序が変更されて、Excelスプレッドシートに書き出されます。
import numpy as np
import pandas as pd
input_file = "mydata.csv"
# comma delimited is the default
df = pd.read_csv(input_file, header = 0)
# for space delimited use:
# df = pd.read_csv(input_file, header = 0, delimiter = " ")
# for tab delimited use:
# df = pd.read_csv(input_file, header = 0, delimiter = "\t")
# put the original column names in a python list
original_headers = list(df.columns.values)
# remove the non-numeric columns
df = df._get_numeric_data()
# put the numeric column names in a python list
numeric_headers = list(df.columns.values)
# create a numpy array with the numeric values for input into scikit-learn
numpy_array = df.as_matrix()
# reverse the order of the columns
numeric_headers.reverse()
reverse_df = df[numeric_headers]
# write the reverse_df to an excel spreadsheet
reverse_df.to_excel('path_to_file.xls')