http://blog.csdn.net/qq_16234613/article/details/64217337html
1.讀取數據python
import pandas as pd data = pd.read_csv("census.csv") # 成功 - 顯示第一條記錄 display(data.head(n=1)) #這個 data 類型是 DataFrame
讀取 寫入
read_csv to_csv
read_excel to_excel
read_hdf to_hdf
read_sql to_sql
read_json to_json
read_msgpack (experimental) to_msgpack (experimental)
read_html to_html
read_gbq (experimental) to_gbq (experimental)
read_stata to_stata
read_sas
read_clipboard to_clipboard
read_pickle to_pickle//速度比csv快 git
#存儲爲csv文件 submission = pd.DataFrame({ 'PassengerId': test_df['PassengerId'],'Survived': predictions }) submission.to_csv("submission.csv", index=False) # index參數是否寫入行names鍵
2.獲取某一列github
#獲取列名爲 income 的一列 income_raw = data['income'] income = data.loc[:,'income'] #獲取列名爲 name 和income 的兩列 sub_data = data.loc[:,['name','income']] #獲取第1列,注意是從0開始 sub_Data1 = data.iloc[:,1] #:表示一整列數據,也能夠選一個區間,如選前兩行 [0,2) sub_Data1 = data.iloc[0:2,1]
3.統計每一個值出現的個數sql
income_value_counts = income.value_counts() #返回的是 pandas.Series類型
4.Series 基礎概念及屬性json
class pandas.
Series
(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)[source]api
One-dimensional ndarray with axis labels (including time series).數組
Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as NaN).數據結構
Operations between Series (+, -, /, , *) align values based on their associated index values– they need not be the same length. The result index will be the sorted union of the two indexes.app
Series 是一個一維數組的數據結構,同時帶有標籤(lable)或者說索引(index)。 numpy.ndArray 裏的統計函數已經被重寫以便於自動除去缺失的數據如 NaN。
Series 之間使用運算符(+, -, /, , *)是基於它們每一個元素進行運算,兩個Series長度不要求一致。也就是說在pandas的Series中,會保留NumPy的數組操做(用布爾數組過濾數據,標量乘法,以及使用數學函數),並同時保持引用的使用。
(這個跟 Numpy的ndArray 是差很少的。舉個 ndArray 的官方例子:)
>>> x = np.array([1, 2]) >>> y = np.array([[3], [4]]) >>> x array([1, 2]) >>> y array([[3], [4]]) >>> x + y array([[4, 5], [5, 6]])
再補一下知識點:
咱們已經瞭解了Python支持布爾類型的數據,布爾類型只有True
和False
兩種值,可是布爾類型有如下幾種運算:
與運算:只有兩個布爾值都爲 True 時,計算結果才爲 True。
True and True # ==> True True and False # ==> False False and True # ==> False False and False # ==> False
或運算:只要有一個布爾值爲 True,計算結果就是 True。
True or True # ==> True True or False # ==> True False or True # ==> True False or False # ==> False
非運算:把True變爲False,或者把False變爲True:
not True # ==> False not False # ==> True
布爾運算在計算機中用來作條件判斷,根據計算結果爲True或者False,計算機能夠自動執行不一樣的後續代碼。
在Python中,布爾類型還能夠與其餘數據類型作 and、or和not運算,請看下面的代碼:
a = True print a and 'a=T' or 'a=F'
計算結果不是布爾類型,而是字符串 'a=T',這是爲何呢?
由於Python把0
、空字符串''
和None
當作 False,其餘數值和非空字符串都當作 True,因此:
True and 'a=T' 計算結果是 'a=T' 繼續計算 'a=T' or 'a=F' 計算結果仍是 'a=T'
另外布爾值還能夠作數字運算,此時 True=1,False=0
a=True
b=False
c=a+b
print c
>>>1
因此求預測結果的準確率的方法能夠以下(通過上面那麼多的鋪墊,其實就是爲了看明白下面這一行代碼。。。)
def accuracy_score(truth, pred): """ 返回 pred 相對於 truth 的準確率 """ # 確保預測的數量與結果的數量一致 if len(truth) == len(pred): # 計算預測準確率(百分比) return "Predictions have an accuracy of {:.2f}%.".format((truth == pred).mean()*100) else: return "Number of predictions does not match number of outcomes!"
Python 基本數據類型 List 若是用+,則是連接兩個數組,同字符串類型。
5.獲取 Series 裏面的某個 key 的值
# 被調查者的收入大於$50,000的人數, #例如income這列的值只有'<=50K'和'>50K' #income.value_counts()輸出以下 # <=50K 34014 # >50K 11208 n_greater_50k = income.value_counts().get('>50K') #value_counts()是通過排序的,若是拿最多的一個數,則能夠用 n_most_group = income.value_counts().index[0]
Series都是指針,要獲取真正的值能夠用.values
獲取第i個元素能夠這樣寫 a.values[i],
6.分割數據
# 將數據切分紅特徵和對應的標籤 income_raw = data['income'] features_raw = data.drop('income', axis = 1)
7.對每一行或每一列應用函數:
def num_missing(x): return sum(x.isnull()) #應用列: print data.apply(num_missing, axis=0) #應用行: print data.apply(num_missing, axis=1).head() # 對於傾斜的數據使用Log轉換,注意 lambda skewed = ['capital-gain', 'capital-loss'] features_raw[skewed] = data[skewed].apply(lambda x: np.log(x + 1))
8.對於