python小点dian儿:DataFrame 取一列类型series 或者 DataFrame

版权声明:欢迎分享和转载,请注明出处 shuihupo:https://blog.csdn.net/shuihupo.同时,本博客部分会在云南省高校数据化运营管理工程中心博客同步。欢迎沟通交流:[email protected] https://blog.csdn.net/shuihupo/article/details/82990052

发现一个小点dian儿

一个 DataFrame 取一列,不同的表示方法,名字是不是列表,会影响得到的结果的类型series 或者 DataFrame. 

python果真是好入手,不好学精呀,之前一直知道取一列后类型会改变问serious,每次都要小心的进行处理,现在发现了这个奥妙,Python也真是强。

print("------df---------")
print(df)
print("---------------")
print('''type(df.ix[:,"key"]''',type(df.ix[:,"key"]))
print(df.ix[:,"key"])
# print(df.ix[:,"key"].reshape(-1))
print('''type(df.ix[:,["key"]]''',type(df.ix[:,["key"]]))
print(df.ix[:,["key"]])
# print(df.ix[:,["key"]].reshape(-1))
------df---------
  data1    key  sorce
0     a  green     33
1     b    red     61
2     c   blue     99
---------------
type(df.ix[:,"key"] <class 'pandas.core.series.Series'>
0    green
1      red
2     blue
Name: key, dtype: object
type(df.ix[:,["key"]] <class 'pandas.core.frame.DataFrame'>
     key
0  green
1    red
2   blue

我为什么会发现这个,是因为我在使用GridSearchCV 时,我的y是一列,当我在纳闷他不就是series的时候,我注意到它在原有df上取一列的时候,列名被[“name”],导致我在print(df.ix[:,["key"]].reshape(-1)) 时候报错,“'DataFrame' object has no attribute 'reshape'”,我才反观我的y,发现了这个奥妙,通过测试证明猜测。

小点dian 儿:GridSearchCV为什么要求series呢,

在将其传递给交叉验证函数之前,需要把标签列变为一维。

from sklearn.grid_search import GridSearchCV  

 小点dian 儿:reshape(-1)

当z只有一列

z.reshape(-1)
z.reshape(-1)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])

当z是一个二维 

z.reshape(-1, 1)

也就是说,先前我们不知道z的shape属性是多少,但是想让z变成只有1列,行数不知道多少,通过`z.reshape(-1,1)`,Numpy自动计算出有16行,新的数组shape属性为(16, 1),与原来的(4, 4)配套。

猜你喜欢

转载自blog.csdn.net/shuihupo/article/details/82990052
今日推荐