![Python之Pandas使用系列(十):數據科學家的pandas快速參考手冊](http://p2.ttnews.xyz/loading.gif)
介紹
我希望本指南能成為一個輕鬆的快速參考手冊,以刷新您在Pandas中的數據處理技能。
注意: 您可以隨意使用任何數據集。
Pandas常用關鍵字:
Dataframe: 類似於電子表格的數據的二維結構
Series: 固定數據類型的一維索引數組
首先,讓我們加載pandas
<code>import pandas as pd
url = “https://raw.githubusercontent.com/jokecamp/FootballData/master/Germany/Bundesliga/1964/matches.csv"/<code>
- 您可以從Internet加載數據而無需下載
<code>data = pd.read_csv(url)
data.head()/<code>
從url讀取數據
(注意:tail()命令從tail中選擇行,您也可以將數字參數傳遞給head和tail命令)
您可以對pandas使用一些 exploratory data analysis(EDA) commands:
<code># print column names
data.columns# print general information about dataframedata.info()# STATISTICS of non-numerical fields (explicitely indicate data #types of interest in include parameterdata.describe(include=[‘object’, ‘bool’])#(Also don’t forget to try with only describe())# For categorical(type object) and boolean(type bool) features, we #can use value_counts method to count the number of values.data[‘home_team’].value_counts()# If you want to calculate porportions try this:data[‘home_team’].value_counts(normalize=True)# Get min and max value from columndata[‘round’].min()data[‘round’].max()# Calculate mean of a columndata[‘round’].mean()/<code>
- DataFrame Indexing
可以通過列名(label),行名(index)或行的序列號對DataFrame進行索引。
loc: 按名稱索引
<code># Get 5 rows from home_score column to away_team column
data.loc[0:5, ‘home_score’:’away_team’]/<code>
iloc: 按數字索引
<code># Same thing as above but using numbers
data.iloc[0:5, 2:5]/<code>
2.更改列中的值
<code>data[‘away_score’] = data[‘away_score’].apply(lambda x: x*2)ORdata[‘away_score’] = data[‘away_score’].str.split(“ “)/<code>
將away_score列加倍
3.添加新列
<code>data[‘new_coumn’] = [i+1000 for i in range(len(data))]/<code>
(注意:使用數組添加新列不是唯一的方法,但是您也可以使用pandas的Series對象在數據框中創建列。)
4.將function應用於多列
<code>data[[‘away_score’,’new_coumn’]] = data[[‘away_score’,’new_coumn’]].apply(lambda x: x*2)/<code>
(注意:您只需要傳遞要修改的列的列表即可。)
5.用NaN計數行
看看有多少行為空
6.選擇NaN行並進行一些操作
選擇帶有Nan的註釋列的行
重要提示:填充NaN行是單獨的主題,不在本文的討論範圍之內。填充缺失值的方法有很多,例如用均值,中位數,最高頻率等填充。但是,如果要填充一些恆定值,則非常簡單:
<code>data.fillna(0)/<code>
7.選擇非NaN行並進行一些操作
<code>data[data[‘notes’].notnull()]/<code>
選擇帶有非nan值的註釋列的行
8.填充NaN行
<code>data.fillna(value = “Replace NaN”, inplace = True)/<code>
用“ Replace Nan”字符串替換nan值
9.將行追加到數據框
<code>data = data.append({ “round”: 5, “home_team”: “Some name”, “home_score”: 0, “away_score”: 50, “away_team”: “some team”, “notes”: “nothing”, “new_coumn”: “Nothing”}, ignore_index=True)data.tail(5)/<code>
將行追加到Dataframe
10.排序並重新索引數據框
<code>data = data.sort_values([‘round’], ascending=False)# If you want to sort by multiple columns, just pass list of columnsdata = data.sort_values(by=[‘round’, ‘away_score’], ascending=[1,0])data.head()/<code>
按降序排序
11.更新列
<code>data.index = range(1, len(data)+1)data.head()/<code>
排序後重新索引數據框
12.使用按位運算的鏈接條件
<code>data[(data[‘notes’] == “Replace NaN”) & (data[‘round’] > 25)]Note: Use | for OR conidtion/<code>
在數據框的列上應用和操作
13.打印列類型
(注意:對於字符串,它使用的是“對象”數據類型)
14.按列類型選擇
<code>import numpy as np
data.loc[:, (data.dtypes == np.dtype(‘O’)).values].head()# Note: ‘O’ means object type. if you want floats use ‘float64’ #instead./<code>
選擇對象數據類型
15.轉換列類型
<code>data[‘away_score’] = data[‘away_score’].astype(float)/<code>
16.條件測試
<code>mydata = [ [1,2,3], [4,5,6] ]
df = pd.DataFrame(mydata)
df < 2/<code>
如果在數據框上測試
17.迭代數據框上的行
注意:我不建議您在數據幀的行上循環並執行操作,但是如果有必要您必須進行迭代,請使用以下方法:
<code>for index, row in data.iterrows():
name = row[‘name’]
age = row[‘age’]
# do some operation/<code>
18.將數據框導出為CSV
如果您想與團隊中的某人共享結果,請先做,然後以CSV格式導出結果,然後將其導入到Google表格中並共享:
<code>data.to_csv(‘result_file.csv’)/<code>
總結:
本文是快速入門,可以幫助您完善使用Pandas數據框的概念。、
如果您喜歡我的文章,請不要忘記在媒體上關注我。
閱讀更多 數據大視界 的文章
關鍵字: 2019未來科學大獎 Python 鏡音雙子