這是油管上的一個帥哥的網課地址以下 https://www.youtube.com/watch?v=yzIMircGU5I&list=PL5-da3qGB5ICCsgW1MxlZ0Hq8LL5U3u9yhtml
# 傳統方式
import pandas as pd
# 直接從URL中讀取Chipotle訂單的數據集,並將結果存儲在數據庫中
url1 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/chipotle.tsv"
#定義地址
orders =pd.read_table(url1)#使用read_table()打開
# 檢查前5行
orders.head()
Documentation for read_table
python
# 讀取電影評論員的數據集(修改read_table的默認參數值)
user_cols = ['user_id','age','gender','occupation','zipcode']#定義列名
url2 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/u.user"
#定義地址
#users=pd.read_table(url2,sep='|',header=None,names= user_clos,skiprows=2,skipfooter=3)
users = pd.read_table('http://bit.ly/movieusers', sep='|', header=None, names=user_cols)
#加入參數sep 分隔符,header 頭部 標題,names 列名
# 檢查前5行
users.head()
[Back to top]git
# 將UFO報告的數據集讀入DataFrame
url3 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv"#定義列名
ufo = pd.read_table(url3, sep=',')
# #用read_table打開csv文件,區別是 read_csv直接是用逗號隔開
ufo = pd.read_csv(url3)
# 檢查前5行
ufo.head()
# #用括號法查看Series
ufo['City']
# #用點法查看Series,要注意 名字裏面有空格或者是python專有字符的時候不能用,可是方便輸入
ufo.City
括號表示法老是有效,而點表示法有侷限性:github
# #這裏的拼接也不能用點的方法
ufo['Location'] = ufo.City + ', ' + ufo.State
ufo.head()
[Back to top]正則表達式
# 將頂級IMDb電影的數據集讀入DataFrame
url4="https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv"
movies = pd.read_csv(url4)
#方法以括號結尾,而屬性則沒有:數據庫
# 示例方法:顯示前5行
movies.head()
#示例方法:計算摘要統計信息
movies.describe()
movies.describe(include=['object'])
# 示例屬性:行數和列數
movies.shape
# 示例屬性:每列的數據類型
movies.dtypes
# 使用describe方法的可選參數來僅彙總'object'列
movies.describe(include=['object'])
Documentation for describe
api
[Back to top]app
# 檢查列名稱
ufo.columns
# 使用'rename'方法重命名其中兩列
ufo.rename(columns={'Colors Reported':'Colors_Reported', 'Shape Reported':'Shape_Reported'}, inplace=True)
ufo.columns
Documentation for rename
ide
# 經過覆蓋'columns'屬性替換全部列名
ufo = pd.read_table(url3, sep=',')
ufo_cols = ['city', 'colors reported', 'shape reported', 'state', 'time']
ufo.columns = ufo_cols
ufo.columns
# 使用'names'參數替換文件讀取過程當中的列名
ufo = pd.read_csv(url3, header=0, names=ufo_cols)
ufo.columns
Documentation for read_csv
函數
ufo.columns = ufo.columns.str.replace(' ', '_') #如何批量修改替換使得列名無空格
ufo.columns
Documentation for str.replace
ufo = pd.read_table(url3, sep=',')
ufo.head()
# #axis=1 是縱向,inplace = True:不建立新的對象,直接對原始對象進行修改;
ufo.drop('Colors Reported', axis=1, inplace=True)
ufo.head()
Documentation for drop
# 一次刪除多個列
ufo.drop(['City', 'State'], axis=1, inplace=True)
ufo.head()
# 一次刪除多行(axis = 0表示行)
ufo.drop([0, 1], axis=0, inplace=True)
ufo.head()
#刪除4行 按標籤,axis=0 是橫向,默認爲橫向,但建議寫出來
movies.head()
#注意:如下任何排序方法都不會影響基礎數據。 (換句話說,排序是暫時的)。
#排序單個Series
movies.title.sort_values().head()
# #排序單個Series 倒序
movies.title.sort_values(ascending=False).head()
Documentation for sort_values
for a Series. (Prior to version 0.17, use order
instead.)
# #以單個Series排序DataFrame
movies.sort_values('title').head()
# 改成按降序排序
movies.sort_values('title', ascending=False).head()
Documentation for sort_values
for a DataFrame. (Prior to version 0.17, use sort
instead.)
# 首先按'content_rating',而後按duration'排序DataFrame
movies.sort_values(['content_rating', 'duration']).head()
Summary of changes to the sorting API in pandas 0.17
movies.head()
# 檢查行數和列數
movies.shape
##目標:過濾DataFrame行,僅顯示「持續時間」至少爲200分鐘的電影
#
#先展現一個比較複雜的方法,用一個for循環制造一個和原數據同樣行數,判斷每一行是否符合條件,列表元素均爲boolean
#建立一個列表,其中每一個元素引用一個DataFrame行:若是行知足條件,則返回true,不然返回False
booleans = []
for length in movies.duration:
if length >= 200:
booleans.append(True)
else:
booleans.append(False)
# 確認列表與DataFrame的長度相同
len(booleans)
# 檢查前五個列表元素
booleans[0:5]
# 將列表轉換爲Series
is_long = pd.Series(booleans)
is_long.head()
# 使用帶有布爾Series的括號表示法告訴DataFrame movies[is_long]要顯示哪些行
movies[is_long]
# 簡化上面的步驟:不須要編寫for循環來建立is_long'
is_long = movies.duration >= 200
movies[is_long]#運用這種寫法,pandas就知道,按照這個series去篩選
# 或等效地,將其寫在一行(無需建立'is_long'對象)
movies[movies.duration >= 200]
# 從過濾後的DataFrame中選擇「流派」系列
movies[movies.duration >= 200].genre
# 或者等效地,使用'loc'方法
movies.loc[movies.duration >= 200, 'genre']
Documentation for loc
# read a dataset of top-rated IMDb movies into a DataFrame
movies = pd.read_csv('http://bit.ly/imdbratings')
movies.head()
# 過濾DataFrame僅顯示「持續時間」至少爲200分鐘的電影
movies[movies.duration >= 200]
理解邏輯運算符:
and
:僅當運算符的兩邊都爲True時才爲真or
:若是運算符的任何一側爲True,則爲真
print(True and True)
print(True and False)
print(False and False)
print(True or True)
print(True or False)
print(False or False)
在pandas中指定多個過濾條件的規則:
使用&而不是和 使用|而不是或 在每一個條件周圍添加括號以指定評估順序
Goal: Further filter the DataFrame of long movies (duration >= 200) to only show movies which also have a 'genre' of 'Drama'
# 使用'&'運算符指定兩個條件都是必需的
movies[(movies.duration >=200) & (movies.genre == 'Drama')]
# I不正確:使用'|'運算符會展現長或戲劇的電影
movies[(movies.duration >=200) | (movies.genre == 'Drama')].head()
##過濾原始數據框以顯示「類型」爲「犯罪」或「戲劇」或「動做」的電影
# 使用'|'運算符指定行能夠匹配三個條件中的任何一個
movies[(movies.genre == 'Crime') | (movies.genre == 'Drama') | (movies.genre == 'Action')].head(10)
# 用isin等效
movies[movies.genre.isin(['Crime', 'Drama', 'Action'])].head(10)
Documentation for isin
Question: When reading from a file, how do I read in only a subset of the columns?
url3 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv"#定義列名
ufo = pd.read_csv(url3)#用read_csv打開csv文件
ufo.columns
# 列名篩選
ufo = pd.read_csv(url3, usecols=['City', 'State'])
# 用位置切片等效
ufo = pd.read_csv(url3, usecols=[0, 4])
ufo.columns
Question: When reading from a file, how do I read in only a subset of the rows?
# 讀3行數據
ufo = pd.read_csv(url3, nrows=3)
ufo
Documentation for read_csv
Question: How do I iterate through a Series?
# Series可直接迭代(如列表)
for c in ufo.City:
print(c)
Question: How do I iterate through a DataFrame?
# 可使用各類方法迭代DataFrame
for index, row in ufo.iterrows():
print(index, row.City, row.State)
Documentation for iterrows
Question: How do I drop all non-numeric columns from a DataFrame?
# 將酒精消耗數據集讀入DataFrame,並檢查數據類型
url7= 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/drinks.csv'
drinks = pd.read_csv(url7)
drinks.dtypes
# 僅包含DataFrame中的數字列
import numpy as np
drinks.select_dtypes(include=[np.number]).dtypes
Documentation for select_dtypes
Question: How do I know whether I should pass an argument as a string or a list?
# 描述全部數字列
drinks.describe()
# 傳遞字符串'all'來描述全部列
drinks.describe(include='all')
# 傳遞數據類型列表以僅描述多個類型
drinks.describe(include=['object', 'float64'])
# 即便您只想描述單個數據類型,也要傳遞一個列表
drinks.describe(include=['object'])
Documentation for describe
url7= 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/drinks.csv'
drinks = pd.read_csv(url7)
drinks.head()
# drop a column (temporarily)
drinks.drop('continent', axis=1).head()
Documentation for drop
# 刪除一列(暫時)
drinks.drop(2, axis=0).head()
使用axis參數引用行或列時:
axis 0表示行 axis 1指的是列
# 計算每一個數字列的平均值
drinks.mean()
# 或等效地,明確指定軸
drinks.mean(axis=0)
Documentation for mean
# 計算每一行的平均值
drinks.mean(axis=1).head()
使用axis參數執行數學運算時:
# 'index' 等效 axis 0
drinks.mean(axis='index')
# 'columns' 等效 axis 1
drinks.mean(axis='columns').head()
url1 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/chipotle.tsv"
#定義地址
orders =pd.read_table(url1)#使用read_table()打開
orders.head()
# 在Python中訪問字符串方法的經常使用方法
'hello'.upper()
# spandas Series 的字符串方法經過'str'訪問
orders.item_name.str.upper().head()
# string方法'contains'檢查子字符串並返回一個布爾Series
orders.item_name.str.contains('Chicken').head()
# 布爾Series篩選DataFrame
orders[orders.item_name.str.contains('Chicken')].head()
# 字符串方法能夠連接在一塊兒
orders.choice_description.str.replace('[', '').str.replace(']', '').head()
# 許多pandas字符串方法支持正則表達式
orders.choice_description.str.replace('[\[\]]', '').head()
String handling section of the pandas API reference
url7= 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/drinks.csv'
drinks = pd.read_csv(url7)
drinks.head()
# 檢查每一個系列的數據類型
drinks.dtypes
# 更改現有系列的數據類型
drinks['beer_servings'] = drinks.beer_servings.astype(float)
drinks.dtypes
Documentation for astype
# 或者,在讀取文件時更改系列的數據類型
drinks = pd.read_csv(url7, dtype={'beer_servings':float})
drinks.dtypes
orders = pd.read_table(url1)
orders.head()
# 檢查每一個系列的數據類型
orders.dtypes
# 將字符串轉換爲數字以進行數學運算
orders.item_price.str.replace('$', '').astype(float).mean()
# 字符串方法'contains'檢查子字符串並返回一個布爾系列
orders.item_name.str.contains('Chicken').head()
# 將布爾系列轉換爲整數(False = 0,True = 1)
orders.item_name.str.contains('Chicken').astype(int).head()
drinks = pd.read_csv(url7)
drinks.head()
# 計算整個數據集中的平均beer_servings
drinks.beer_servings.mean()
# 計算非洲國家的平均beer_servings
drinks[drinks.continent=='Africa'].beer_servings.mean()
#計算每一個大陸的平均beer_servings
drinks.groupby('continent').beer_servings.mean()
Documentation for groupby
# 其餘聚合函數(例如'max')也能夠與groupby一塊兒使用
drinks.groupby('continent').beer_servings.max()
# 多個聚合函數能夠同時應用
drinks.groupby('continent').beer_servings.agg(['count', 'mean', 'min', 'max'])
Documentation for agg
# 不指定列,就會算出全部數值列
drinks.groupby('continent').mean()
# 容許繪圖出如今jupyter notebook中
%matplotlib inline
# 直接在上面的DataFrame的並排條形圖
drinks.groupby('continent').mean().plot(kind='bar')
Documentation for plot
# read a dataset of top-rated IMDb movies into a DataFrame
url4="https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv"
movies = pd.read_csv(url4)
movies.head()
# 檢查數據類型
movies.dtypes
探索非數字系列
# 計算最多見值的非空值,惟一值和頻率
movies.genre.describe()
Documentation for describe
# 數Series中每一個值發生的次數
movies.genre.value_counts()
Documentation for value_counts
# 顯示百分比而不是原始計數
movies.genre.value_counts(normalize=True)
# '輸出的是一個Series
type(movies.genre.value_counts())
# 可使用Series方法
movies.genre.value_counts().head()
# 顯示Series中惟一值
movies.genre.unique()
#數Series中惟一值的數量
movies.genre.nunique()
# 兩個Series的交叉列表
pd.crosstab(movies.genre, movies.content_rating)
Documentation for crosstab
探索數字系列:
# 計算各類彙總統計
movies.duration.describe()
# 許多統計數據都是做爲Series方法實現的
movies.duration.mean()
Documentation for mean
# 'value_counts' 主要用於分類數據,而不是數字數據
movies.duration.value_counts().head()
# 容許繪圖出如今jupyter notebook中
%matplotlib inline
# 'duration'Series的直方圖(顯示數值變量的分佈)
movies.duration.plot(kind='hist')
# 'genre'Series'value_counts'的條形圖
movies.genre.value_counts().plot(kind='bar')
Documentation for plot
原文出處:https://www.cnblogs.com/romannista/p/10659805.html