Python切片符号

时间:2018-10-01 18:07:41

标签: python pandas machine-learning data-science

我试图理解来自machinelearningmastery.com的一些示例代码,但是切片符号让我望而却步。。。文件:

import pandas as pd

McheLrn = pd.read_csv('C:/Users/data.csv', index_col='Date', parse_dates=True)


McheLrn['month'] = McheLrn.index.month
McheLrn['date'] = McheLrn.index.strftime('%d')
McheLrn['hour'] = McheLrn.index.strftime('%H')
McheLrn['Day_of_week'] = McheLrn.index.dayofweek

McheLrn.head()

这将输出:

    OSAT    kWh month   date    hour    Day_of_week
Date                        
2013-01-01 06:00:00 10.4    16.55   1   01  06  1
2013-01-01 06:15:00 10.4    16.55   1   01  06  1
2013-01-01 06:30:00 10.4    16.05   1   01  06  1
2013-01-01 06:35:00 10.4    16.05   1   01  06  1
2013-01-01 06:45:00 10.4    17.20   1   01  06  1

不确定我是否使用了正确的术语,但是因变量是kWh(Y变量),而其他所有变量都是X变量的自变量...

使用下面的代码使切片符号X = array[:,0:2] Y = array[:,2]令人困惑,而且我不确定是否正确选择了X和Y变量。

# Decision Tree Regression
import pandas
from sklearn import model_selection
from sklearn.tree import DecisionTreeRegressor


dataframe = McheLrn
array = dataframe.values

X = array[:,0:2]
Y = array[:,2]

seed = 7
kfold = model_selection.KFold(n_splits=90, random_state=seed)
model = DecisionTreeRegressor()
scoring = 'neg_mean_squared_error'
results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring)

print(results.mean())

1 个答案:

答案 0 :(得分:1)

仅作进一步说明。如果您知道目标列(名称),那么首选方法是选择除目标列之外的所有内容

df=pd.DataFrame({'a':[1,2],'b':[2,3],'c':[1,9]})
target_col=['c'] # column 'c' is the target column here
X=df[list(set(df.columns).difference(target_col))].values # X-> features
Y=df[target_col].values # Y -> target

如果使用列号。假设最后一列是目标列

data=df.values
X=data[:,:2] # from column 1 upto second last column including all the rows
Y=data[:,2] # only last column(target) including all the rows
相关问题