2018.9.26——2018.10.22
-
Introduction To NumPy
1.常規(guī)操作是先用 csv模塊讀取文件帅霜,然后list之使其變成list of list的格式弥虐,最后再用np.array將其轉(zhuǎn)化
總而言之,就是先用csv模塊讀取
f = open("nyc_taxis.csv", "r")
taxi_list = list(csv.reader(f))
處理一下片效,去除第一項(xiàng)的標(biāo)題項(xiàng)
taxi_list = taxi_list[1:]
將全部value轉(zhuǎn)化為float
converted_taxi_list = []
for row in taxi_list:
—converted_row = []
—for item in row:
——converted_row.append(float(item))
—converted_taxi_list.append(converted_row)
然后用np.array處理之
taxi = np.array(converted_taxi_list)
2.可以使用taxi.shape來(lái)查看其中的結(jié)構(gòu)
輸出會(huì)類似(100,20),意思是說(shuō)在第一個(gè)dimension有100個(gè)數(shù)值呼渣,即100行蔑祟,20列。
3.taxi[:5]注意一下這是選取前五行
4.6.同維度的array之間可以加減乘除
trip_length_hours = trip_length_seconds / 3600
trip_mph = trip_distance_miles / trip_length_hours
除了直接用除法/,numpy包也可以使用np.divide功能來(lái)實(shí)現(xiàn)同樣的操作
trip_mph_2 = np.divide(trip_distance_miles,trip_length_hours)
7.function與method的對(duì)比
最小值
np.min(trip_mph) VS trip_mph.min()
最大值
np.max(trip_mph) VS trip_mph.max()
平均值
np.mean(trip_mph) VS trip_mph.mean()
中位數(shù)
np.median(trip_mph)
8.如果是個(gè)2d ndarrary
ndarrary.max()輸出的只是其中數(shù)值最大的一個(gè)數(shù)
ndarrary.max(axis = 1)會(huì)輸出每一行最大的數(shù)組成列大脉,同理如果axis = 0搞监,就會(huì)輸出每一列最大的數(shù)組成一行
9.如果要在arrary上加一行或者一列應(yīng)該如何做?
首先要查看倆arrary的結(jié)構(gòu)是否相匹配镰矿,print(arrary.shape)
例如如果是(2, 3)與(3,)就不行琐驴,前者是二維arrary,后者是一維衡怀,所以要先把后者轉(zhuǎn)化成二維
np.expand_dims(zeros,axis=0)因?yàn)槭菍⒁痪S轉(zhuǎn)化為二維且形式是行棍矛,所以axis = 0
此時(shí)一維的(3,)就變成了二維的(1,3)
然后combined = np.concatenate([ones,zeros_2d],axis=0)其中np.concatenate(),中括號(hào)內(nèi)為相合并的兩個(gè)array,因?yàn)槭切泻喜⑴籽睿詀xis = 0
10.有關(guān)排序
對(duì)于某一個(gè)[X, X, X, X]使用np.argsort可將其排序(按數(shù)字大小或者開頭字母順序)够委,輸出得到的是序列號(hào),例如如果是[2,3,1]排序后輸出的就是[2, 0, 1]怖现,因?yàn)?應(yīng)該排在第一位茁帽,但是卻排在了最后,所以排序后的序列號(hào)第一個(gè)就是1的位置屈嗤,然后是2的位置潘拨,3的位置這樣。
sorted_order = np.argsort(last_column)
然后按一下方法可以輸出排序后[X, X, X, X]是什么樣子的
last_column_sorted = last_column[sorted_order]
最后就可以根據(jù)那一行/一列的排序來(lái)使原始整個(gè)array都發(fā)生了行/列的順序替換
int_square_sorted = int_square[sorted_order]
-
Boolean Indexing With NumPy
1.讀取csv文件,間隔符是逗號(hào),去除首行標(biāo)題(注意一下去除首行標(biāo)題skip_header=1而不是0)
taxi = np.genfromtxt('nyc_taxis.csv', delimiter=',', skip_header=1)
2.布爾與arrary
輸入np.array([2,4,6,8]) < 5
輸出array([ True, True, False, False], dtype=bool)
每個(gè)element會(huì)單獨(dú)檢驗(yàn)一次會(huì)不會(huì)小于5
此外數(shù)組直接計(jì)算也是可以的
輸入np.array([2,4,6,8]) + 10
輸出array([12, 14, 16, 18])
3.新的套路
查詢一個(gè)一位數(shù)組中=1的分別是哪些
january_bool = pickup_month == 1(得到的是一個(gè)布爾數(shù)組)
再選出數(shù)組中值為1的element
january = pickup_month[january_bool]
最后計(jì)算一下值為1的element有多少個(gè)妈拌?章郁??纯命?
january_rides = january.shape[0]??涩禀??
4.ndarray.copy()修改復(fù)制數(shù)組然眼,對(duì)原數(shù)組沒有影響
如taxi_modified = taxi.copy()
5.c[c[:,1] > 2, 1] = 99
如果第二列有大于2的數(shù)艾船,那么那個(gè)數(shù)就變成99
-
Introduction To Pandas
import pandas as pd
1.導(dǎo)入數(shù)據(jù),格式為dataframe(此處指定第一列為行標(biāo)題)
f500 = pd.read_csv("f500.csv", index_col=0)
f500.index.name = None 因?yàn)樵瓟?shù)據(jù)中高每,第一列(現(xiàn)在作為行標(biāo)題)原本應(yīng)該也是有自己的標(biāo)題的屿岂,這里就是比如company:X1,X2....現(xiàn)在X1 X2都是作為每一行的標(biāo)題了鲸匿,這里就是將company刪去
2.f500_type = type(f500)查看數(shù)據(jù)類型爷怀,比如此處就是dataframe
f500_shape = f500.shape查看這個(gè)數(shù)據(jù)類型是幾行幾列,比如(500,16)就是500行16列
4.label selection methods 匯總
5.選取前n行
df.head(n)
6.選取哪幾行哪幾列
big_movers = f500.loc[["row1", "row2"], ["column1", "column2"]]
7.pandas包中的describe()function晒骇,參照R中的summary類似
profits_desc = f500["profits"].describe()一個(gè)dataframe中的一列的總結(jié)
revenue_and_employees_desc = f500[["revenues", "employees"]].describe()一個(gè)dataframe中的兩列的總結(jié)
all_desc = f500.describe(include="all")整個(gè)dataframe的是總結(jié)
8.按dataframe中的series計(jì)數(shù)霉撵,比如此處就是計(jì)算各個(gè)country出現(xiàn)的次數(shù)磺浙,順序是從多到少
top5_countries = f500['country'].value_counts()
top5_countries = f500['country'].value_counts().head(10)更進(jìn)一步為前十個(gè),如果head括號(hào)內(nèi)不填則默認(rèn)為前五個(gè)
9.找出每一列的最大值徒坡,括號(hào)內(nèi)規(guī)定只作用于數(shù)值型變量
max_f500 = f500.max(numeric_only=True)
類似的還有:
Series.max() and DataFrame.max()
Series.min() and DataFrame.min()
Series.mean() and DataFrame.mean()
Series.median() and DataFrame.median()
Series.mode() and DataFrame.mode()
Series.sum() and DataFrame.sum()
10.dataframe中數(shù)的替換
f500.loc["Dow Chemical","ceo"] = "Jim Fitterling"
其中f500是dataframe,"Dow Chemical"是第一列company中其中的一個(gè)公司撕氧,而ceo是那一行對(duì)應(yīng)的后面某一列,這里是將f500中喇完,第一列Dow Chemical公司的ceo改成"Jim Fitterling"
11.有關(guān)于布爾array
以下是dataframe和series之間的區(qū)別伦泥,可以看到dataframe是展示出所有列,而series只會(huì)展示出選中的列
12.關(guān)于布爾的栗子
kr_bool = f500["country"] == "South Korea"
top_5_kr = f500[kr_bool].head()展示前五個(gè)
13.Series.value_counts()中可以加入dropna=False锦溪,意義是將NaN也計(jì)算進(jìn)去(默認(rèn)是跳過(guò)的)
栗子f500["previous_rank"].value_counts(dropna=False)
14.以下步驟就是將NaN值替換為0的過(guò)程
import numpy as np
prev_rank_before = f500["previous_rank"].value_counts(dropna=False).head()將空值也計(jì)算進(jìn)去
f500.loc[f500["previous_rank"] == 0, "previous_rank"] = np.nan將空值替換為0
prev_rank_after = f500["previous_rank"].value_counts(dropna=False).head()
15.問題:Create a series, cities_usa, containing counts of the five most common Headquarter Location cities for companies headquartered in the USA.
解決:cities_usa = f500.hq_location[f500["country"] == "USA"].value_counts().head()
-
Exploring Data With Pandas
- 對(duì)比一下numpy和pandas
- 在numpy中不脯,格式是數(shù)組,array
ndarray[2, 0]選取的是第三行的第一個(gè)數(shù)
ndarray[1]選取的是第二行 - 在pandas中刻诊,因?yàn)橛衛(wèi)oc,且格式時(shí)dataframe,所以:
df.loc["z", "A"]定位行標(biāo)簽為"z",列標(biāo)簽為"A"
df.loc["y"]定位行標(biāo)簽為"y"
2.Series.iloc和Series.loc
Series.iloc[]括號(hào)內(nèi)是根據(jù)位置來(lái)定位
Series.loc[]括號(hào)內(nèi)是根據(jù)行/列標(biāo)簽的名稱來(lái)定位
3.排序df.sort_values("根據(jù)哪一列的列標(biāo)簽"防楷, 是否升序)
sorted_emp = f500.sort_values("employees", ascending=False)
4.Series.str.endswith("t")測(cè)試這個(gè)series中的每一個(gè)element是否以t結(jié)尾,返回布爾數(shù)值
其中则涯,s.str.endswith('t', na=False)括號(hào)內(nèi)的na=False复局,如果不設(shè)置那么遇到np.nan會(huì)返回NAN,設(shè)置后遇到np.nan就會(huì)單純的返回TRUE/FALSE
同理,類似的還有Series.str.startswith("t")粟判,Series.str.contains("t")
5.pandas中的布爾數(shù)值
pandas中 a & b——a and b python中
pandas中 a | b——a or b python中
pandas中 ~a——not a python中
6.關(guān)于控制與非空值的選取
Series.isnull()查找null值的位置 df[Series.isnull()]就可以選出df中指定Series均為null值的部分
Series.notnull()查找非null值的位置 同上
7.按條件選取
filter_big_rev_neg_profit = (f500["revenues"] > 100000) & (f500["profits"] < 0)
big_rev_neg_profit = f500[filter_big_rev_neg_profit]
8.選出唯一值
Series.unique()
輸出的格式為array
9.eg
countries = f500["country"].unique()
for c in countries:
—selected_rows = f500[f500["country"] == c]
—sorted_rows = selected_rows.sort_values("employees", ascending=False)
—top_employer = sorted_rows.iloc[0]
—employer_name = top_employer["company"]
—top_employer_by_country[c] = employer_name
-
Data Cleaning Basics
1.讀取數(shù)據(jù)csv,此方法讀出來(lái)是dataframe格式
df = pd.read_csv("filename.csv", encoding="UTF-8")
2.dataframe.info()查看該dataframe的信息
3.關(guān)于string的處理
str.strip()去除空格
str.replace(" ",",")用逗號(hào)代替空格
str.lower()改成全小寫亿昏?
def clean_col(col):
—col = col.strip()
—col = col.replace("Operating System", "os")
—col = col.replace(" ","_")
—col = col.replace("(","")
—col = col.replace(")","")
—col = col.lower()
—return col
laptops.columns = [clean_col(c) for c in laptops.columns]
5.pandas.DataFrame.rename重命名
laptops.rename({"ram": "ram_gb"}, axis=1, inplace=True)將列名稱ram重命名為ram_gb,其中axis=1代表列档礁,如果是0代表行
6.df.astype()改變格式
laptops["ram"] = laptops["ram"].astype(int)將ram列內(nèi)的數(shù)據(jù)替換為Int格式
7.某一列的文本中帶有s的element
laptops.loc[laptops["weight"].str.contains('s'), "weight"]
8.進(jìn)行2次replace替換角钩,再加上.astype還可以繼續(xù)改變格式
laptops["weight"] = laptops["weight"].str.replace("kgs","").str.replace("kg","")
9.series.describe()相當(dāng)于R語(yǔ)言中的SUMMARY,提供平均數(shù)呻澜,計(jì)數(shù)递礼,四分位數(shù)等信息
price_describe = laptops["price_euros"].describe()
10.Series.str.split和R的split類似,默認(rèn)是切割空格
s.str.split(n=1,expand=True)從前往后切割易迹,My name is 切割為my 和name is
s.str.rsplit(n=1,expand=True)從后往前切割,My name is 切割為my name 和 is
11.找出錯(cuò)誤的element,然后改正之
有關(guān)Series.map()匹配
x = pd.Series([1,2,3], index=['one', 'two', 'three'])
y = pd.Series(['foo', 'bar', 'baz'], index=[1,2,3])
x.map(y)結(jié)果會(huì)是
one foo
two bar
three baz
即會(huì)以x的key為結(jié)果的key,x中的value去找y的key配對(duì)宰衙,如果是一樣的那么結(jié)果中對(duì)應(yīng)的key就會(huì)輸出value平道,如果x的value在y的key中沒有一樣的睹欲,那么結(jié)果中key對(duì)應(yīng)的value就會(huì)是錯(cuò)誤值NaN
12.去除錯(cuò)誤值/空值
pandas.DataFrame.info對(duì)于該dataframe會(huì)輸出一個(gè)Summary,對(duì)于每一列會(huì)告訴你有多少element一屋,有沒有空值
DataFrame.isnull()會(huì)輸出一個(gè)布爾向量窘疮,告訴這個(gè)位置是否空值
laptops.isnull().sum()得到是不是空值的布爾向量后加上SUM可以分類匯總,即每一列有幾個(gè)空值
DataFrame.dropna()會(huì)移除存在NaN的行或者列冀墨,方法是在括號(hào)內(nèi)axis=0即為移除NaN縮在行闸衫,1為列
13.Series.value_counts()計(jì)算每個(gè)value的個(gè)數(shù),默認(rèn)不會(huì)計(jì)算NaN的null值诽嘉,但是括號(hào)內(nèi)加dropna=False就會(huì)統(tǒng)計(jì)NaN值數(shù)量
14.dataframe.drop去除某一行/列
s = laptops.drop('storage', axis=1,inplace = TRUE/FALSE)其中Inplace為TRUE時(shí)會(huì)取代原有的df蔚出,為FALSE時(shí)原來(lái)的df不改變
15.輸出保存
DataFrame.to_csv()保存為csv格式弟翘,括號(hào)內(nèi)可以為""絕對(duì)路徑
laptops.to_csv('laptops_cleaned.csv',index=False)
-# Guided Project: Exploring Ebay Car Sales Data項(xiàng)目實(shí)踐
1.讀取數(shù)據(jù)pd.read_csv()
2.閱覽數(shù)據(jù)df.info(),df.head()
3.查看每一列的名稱df.columns
4.更換列的名稱,df.rename({"column1":"column1x", ......}, axis=1, inplace=TRUE)
5.查看每一列中數(shù)值的具體情況骄酗,如最大值最小值數(shù)量等autos.describe(include='all')
6.根據(jù)某一列分類計(jì)數(shù)autos['seller'].value_counts()
去除其中某幾列autos.drop(['seller','offer_type','abtest','gearbox','unrepaired_damage'],axis=1)
7.替換內(nèi)容和更改類型
autos['price']=autos['price'].astype('str').str.replace('"].unique().shape
某一列的范圍選取autos[autos["price_$"].between(6.990000e+02,1.090000e+04)]
9.計(jì)數(shù)brands_top5 = autos["brand"].value_counts()
提取index名稱brand_names = brands_top5.index