python小點dian兒:DataFrame 取一列,類型是series 還是 DataFrame?

發現一個小點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)配套。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章