柚子快報激活碼778899分享:Pandas在大氣科學中的應用
柚子快報激活碼778899分享:Pandas在大氣科學中的應用
Pandas簡介
Pandas作為Numpy的升級版本,通常來說應用更加廣泛,是數(shù)據(jù)處理很好用的也很基礎的一個python庫,而且以我的專業(yè)為例,python在大氣科學中的應用絕對少不了讀取數(shù)據(jù)然后處理數(shù)據(jù),因此學習Pandas對我很重要,接下來我也向各位分享我學習的Pandas。
pd.Series? ?------序列?
?序列本質(zhì)上就是一個帶了標簽的numpy.ndarray對象的衍生,因此序列是支持所有關于多維數(shù)組的操作的。【在此要注意的就是pd.Series一定是一維的】
pd.Series(data, index, dtype, name)? ?# data是一維列表或者數(shù)組,index是數(shù)據(jù)對應的索引,dtype就是數(shù)據(jù)類型,name是用于命名對象【index索引可以是時間索引】
例如:
import pandas as pd
import datetime as dt
# 當索引是普通的索引時
data = pd.Series([0.1, 9.8, 7.6, 5.5], index=["a", "b", "c", "d"], name="xiaolv")
# 當索引是時間索引時
# 時間戳是時間協(xié)調(diào)時(UTC【Universal Time coordinated】),如果想要將北京時間(CST【China Standard Time】)轉成時間協(xié)調(diào)時使用
index_time = pd.to_datetime(["2020-2-19", "2020-2-20", "2020-2-21", "2020-2-22"])
index_time -= dt.timedelta(hours=8)
data_time = pd.Series([0.1, 9.8, 7.6, 5.5],
index=index_time, name="xiaolv")
print(data)
print(data_time)
output:
a 0.1
b 9.8
c 7.6
d 5.5
Name: xiaolv, dtype: float64
2020-02-18 16:00:00 0.1
2020-02-19 16:00:00 9.8
2020-02-20 16:00:00 7.6
2020-02-21 16:00:00 5.5
Name: xiaolv, dtype: float64
pd.Series對象的算術運算
pd.Series對象的算術運算和numpy.ndarray對象的運算幾乎完全一樣,廣播運算沒有兩樣,但是兩個同樣維度的pd.Series對象進行運算時根據(jù)他們的索引匹配運算的【對于兩個對象都有的索引是匹配運算,而對于兩個對象特有的某索引python會自動賦予NAN值并且索引擴張】
import pandas as pd
a = pd.Series([1, 2, 3, 4], index=["a", "b", "c", "d"], name="xiaolv")
b = pd.Series([2, 3, 4, 6], index=["a", "c", "e", "d"], name="patience")
print(a+b)
output:
a 3.0
b NaN
c 6.0
d 10.0
e NaN
dtype: float64
?pd.Series對象的常用的一些屬性
.dtype? ? ? ? ? ? ? ?# 輸出pd.Series對象的數(shù)據(jù)的類型
.shape? ? ? ? ? ? ? # 可以輸出pd.Series對象有幾個元素
.at["a"]? ? ? ? ? ? ??# 用標簽索引訪問pd.Series對象的單個元素
.iat[0]? ? ? ? ? ? ? ? # 用數(shù)值索引訪問pd.Series對象的單個元素
.loc[[]]? ? ? ? ? ? ? ?# 用標簽或者布爾序列訪問多個元素【類似于Numpy】
.iloc[[]]? ? ? ? ? ? ? # 用數(shù)值索引訪問多個元素? ?
.values? ? ? ? ? ? ?# 獲取數(shù)據(jù)的原始np.ndarray對象
特別提醒:pd.Series對象可以進行切片索引操作的
import pandas as pd
a = pd.Series([9.1, 9.5, 10.0, 11.2], index=["a", "b", "c", "d"], name="xiaolv")
print(a.at["c"])
print(a.iat[0])
print(a.loc[a > 9.6])
print(a.loc[["a", "b"]])
print(a.iloc[[0, 2, 3]])
print(a.values)
output:
10.0
9.1
c 10.0
d 11.2
Name: xiaolv, dtype: float64
a 9.1
b 9.5
Name: xiaolv, dtype: float64
a 9.1
c 10.0
d 11.2
Name: xiaolv, dtype: float64
[ 9.1 9.5 10. 11.2]
?pd.Series對象的常用方法
.dropna()? ? ? ? ? # 可用于刪除pd.Series對象中的nan值
.groupby()? ? ? ? # 根據(jù)索引對數(shù)據(jù)進行分組,返回一個GroupBy對象,對象自帶min,max,mean等方法,例如b=a.groupby(level=0).mean(),再比如c=a.groupby(a > 9.6).mean()
.sum()/.mean()/.max()/.min()? ? # 求和,求平均,求最大,求最?。ǘ际悄J不統(tǒng)計nan)
.std()? ? ? ? ? ? ? ? # 求標準差
.abs()? ? ? ? ? ? ? ?# 對所有元素求絕對值
.idxmax()/.idxmin()/.argmax()/.argmin()? # 最大值/最小值對應的索引標簽(idx),位置(arg)【index,position argument】
.to_list()? ? ? ? ? # 將其轉化為list對象
.astype()? ? ? ? ?# 轉換所有元素的類型
import pandas as pd
import numpy as np
a = pd.Series([9.1, 9.5, 10.0, 11.2], index=["a", "a", "c", "d"], name="xiaolv")
b = a.groupby(level=0).mean()
c = a.groupby(a > 9.6).mean()
d = a.std()
e = a.idxmax()
f = a.argmax()
g = a.astype(np.int_)
h = a.to_list()
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
print(h)
output:
a 9.3
c 10.0
d 11.2
Name: xiaolv, dtype: float64
xiaolv
False 9.3
True 10.6
Name: xiaolv, dtype: float64
0.9110433579144297
d
3
a 9
a 9
c 10
d 11
Name: xiaolv, dtype: int32
[9.1, 9.5, 10.0, 11.2]
?pd.DataFrame------數(shù)據(jù)框
與Numpy不同的是,pd.DataFrame對象的每一列都可以是不同的數(shù)據(jù)類型(這也是通常使用pandas來讀取csv文件而不用Numpy讀取的原因)
pd.DataFrame(data, index, column, dtype)? # column指的是列索引,一般來說只會把index當做時間索引來操作,而不會把column作為時間索引
import pandas as pd
a = pd.DataFrame([[21.7, 983, 0.64],
[19.2, 991, 0.75],
[13.4, 973, 0.83]],
index=pd.to_datetime(["2020-02-19", "2020-02-20", "2020-02-22"]),
columns=["t", "p", "rh"])
print(a)
output:
t p rh
2020-02-19 21.7 983 0.64
2020-02-20 19.2 991 0.75
2020-02-22 13.4 973 0.83
pd.DataFrame基本操作
一、pd.DataFrame的算術運算
1.與標量運算,相當于直接作用于每一個元素(這種情況很少,因為每一列單位不同)
2.與pd.Series運算,要保證pd.Series的index和pd.DataFrame的column進行對應
3.兩個pd.DataFrame進行運算,就要保證index和column都相等?
二、提取滿足條件的行?
1.按照數(shù)據(jù)條件提取
這和Numpy提取滿足條件的行是一樣的,利用的是類似Numpy數(shù)組的邏輯索引功能,使用bool數(shù)組來進行選取行。當有多個條件的時候和Numpy數(shù)組一樣使用&,|來分隔,每個條件一定需要使用括號括起來才能用?!具@里a["t"]提取之后得到的是numpy.ndarray對象】
例如:print(a[(a["t"] < 20) & (a["p"] > 10)])
2.按照時間索引條件提取
使用類似b= a[a.index.year/month/day == ?]的形式來進行選取,本質(zhì)上還是類似Numpy的bool數(shù)組選取
三、pd.DataFrame的常用屬性
.dtypes? ? ? ? ? ? ? ? ? ? ? ? # 查看每一列的數(shù)據(jù)類型
.at["s1", "t"]? ? ? ? ? ? ? ? ? # 通過行/列標簽索引選取一個元素
.iat[0,0]? ? ? ? ? ? ? ? ? ? ? ? # 通過行/列位置索引選取一個元素
.loc[]? ? ? ? ? ? ? ? ? ? ? ? ? ? # 通過行或者列標簽訪問多個行或者列,注意形成Series或DataFrame
.iloc[]? ? ? ? ? ? ? ? ? ? ? ? ? ?# 通過行或者列位置訪問多個行或者列,用法大同小異
.values? ? ? ? ? ? ? ? ? ? ? ? # 和pd.Series類似,返回np.ndarray對象
特別提醒:pd.DataFrame也是可以進行切片索引操作的。
以下舉例:
import numpy as np
import pandas as pd
data = np.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
datahh = pd.Series([1, 2, 3, 4, 5], index=["2", "3", "4", "5", "6"])
hh = pd.DataFrame(data)
print(hh.loc[0:1, 1:3])
# 必須例如一下[[0, 1], [1, 2, 3]]行列都用列表(這里把切片也看成是列表括起來的)括起來才是DataFrame對象,如果但凡有一個不是列表括起來的都生成DataArray對象。
print(hh.loc[[0, 1], [1, 2, 3]])
print(hh.loc[:, [1, 2]])
print(hh.loc[:, 1])
output:
1 2 3
0 2 3 4
1 2 3 4
1 2 3
0 2 3 4
1 2 3 4
1 2
0 2 3
1 2 3
2 3 4
0 2
1 2
2 3
Name: 1, dtype: int32
import pandas as pd
a = pd.DataFrame([[21.7, 983, 0.64],
[19.2, 991, 0.75],
[13.4, 973, 0.83]],
index=["k", "w", "s"],
columns=["t", "p", "rh"])
print(a.loc[["k"]]) # DataFrame
print(a.loc["k"]) # Series
print(a.loc[:, ["t"]]) # DataFrame
print(a.loc[:, "t"]) # Series
print(a.iloc[:, [0, 1]]) # DataFrame
print(a.iloc[0]) # Series
output:
t p rh
k 21.7 983 0.64
t 21.70
p 983.00
rh 0.64
Name: k, dtype: float64
t
k 21.7
w 19.2
s 13.4
k 21.7
w 19.2
s 13.4
Name: t, dtype: float64
t p
k 21.7 983
w 19.2 991
s 13.4 973
t 21.70
p 983.00
rh 0.64
Name: k, dtype: float64
四、pd.DataFrame的常用方法
1..dropna()? ? ? ? ? ? ? ? ? ? ?
# 刪除包含NaN的行,如果想要刪除包含NaN的列(加axis=1),如果想要刪除全為NaN的行或列就加一個how="all"參數(shù)即可
2..groupby()? ? ? ? ? ? ? ? ? ?
# 分組分類,可以接受level參數(shù)實現(xiàn)通過索引分組或者接受by參數(shù)實現(xiàn)通過列名稱對數(shù)據(jù)進行分組?!酒渲衛(wèi)evel=0,例如by=“kind”指定以kind列為分組依據(jù)】,在分組之后生成一個DataFrameGroupBy對象,摒棄了原索引,索引變成了kind的索引。這個對象擁有sum(),max(),min(),mean()方法
特別提醒:by參數(shù)也可以是一個自定義函數(shù),這相當于將索引(index參數(shù)的值)中的元素逐一輸入函數(shù),然后根據(jù)自定義函數(shù)的輸出值進行分組,相同函數(shù)輸出值所在行分為同一組。
3..max()/min()/idxmax()/idxmin()? ?
# 類似于pd.Series,只不過參數(shù)axis=0時為每列最大值輸出,axis=1時為每行最大值輸出
4..to_csv(fname)? ? ?
# fname是地址?
五、pd.DataFrame讀取csv文件
pd.read_csv(fname, index_col=0)? ? # fname為路徑,index_col為指定索引列所在的位置,如果文件只有索引沒有列名,指定header=None即可。parse_dates=[]可以指定需要讀取的列,可以和index_col聯(lián)合使用
六、pd.DataFrame增加列的方法和merge(),concat()函數(shù)
對于pd.DataFrame對象data,data[""] = pd.Series 就可以增加一列,右端為pd.Series對象。
1.merge()
# merge函數(shù)分為左連接,右連接,內(nèi)連接和外連接
2.concat()?
# 用于合并多個pd.DataFrame,可以按照行或者列合并多個pd.DataFrame。
import pandas as pd
a = pd.DataFrame([["sunny", 983, 0.64],
["rain", 991, 0.75],
["fog", 973, 0.83],
["haze", 1001, 0.93]],
index=["d1", "d2", "d3", "d4"],
columns=["weather", "p", "rh"]
)
b = pd.DataFrame([["rain", "0121"],
["windy", "1123"],
["fog", "1234"],
["sunny", "2234"]],
index=["d1", "d2", "d3", "d4"],
columns=["weather", "code"]
)
print(a)
print(b)
# concat是直接將兩個DataFrame強行合并的,按照是以行合并還是合并用axis=0/1區(qū)分
c = pd.concat([a, b], axis=0) # axis=0是按照行和并
d = pd.concat([a, b], axis=1) # axis=1是按照列合并
print(c)
print(d)
# merge使用之后index都會變成0,1,2...,同時left_on和right_on就是指定左右DataFrame對象是通過什么來確定怎么合并
# left就是保留所有左DataFrame的鍵,同理right就是保留所有右邊鍵,inner就是保留共有的鍵,outer就是保留所有鍵
# 沒有的值用NaN填充
e = pd.merge(a, b, left_on="weather", right_on="weather", how="left")
f = pd.merge(a, b, left_on="weather", right_on="weather", how="right")
g = pd.merge(a, b, left_on="weather", right_on="weather", how="inner")
h = pd.merge(a, b, left_on="weather", right_on="weather", how="outer")
print(e)
print(f)
print(g)
print(h)
output:
weather p rh
d1 sunny 983 0.64
d2 rain 991 0.75
d3 fog 973 0.83
d4 haze 1001 0.93
weather code
d1 rain 0121
d2 windy 1123
d3 fog 1234
d4 sunny 2234
weather p rh code
d1 sunny 983.0 0.64 NaN
d2 rain 991.0 0.75 NaN
d3 fog 973.0 0.83 NaN
d4 haze 1001.0 0.93 NaN
d1 rain NaN NaN 0121
d2 windy NaN NaN 1123
d3 fog NaN NaN 1234
d4 sunny NaN NaN 2234
weather p rh weather code
d1 sunny 983 0.64 rain 0121
d2 rain 991 0.75 windy 1123
d3 fog 973 0.83 fog 1234
d4 haze 1001 0.93 sunny 2234
weather p rh code
0 sunny 983 0.64 2234
1 rain 991 0.75 0121
2 fog 973 0.83 1234
3 haze 1001 0.93 NaN
weather p rh code
0 rain 991.0 0.75 0121
1 windy NaN NaN 1123
2 fog 973.0 0.83 1234
3 sunny 983.0 0.64 2234
weather p rh code
0 sunny 983 0.64 2234
1 rain 991 0.75 0121
2 fog 973 0.83 1234
weather p rh code
0 fog 973.0 0.83 1234
1 haze 1001.0 0.93 NaN
2 rain 991.0 0.75 0121
3 sunny 983.0 0.64 2234
4 windy NaN NaN 1123
柚子快報激活碼778899分享:Pandas在大氣科學中的應用
好文鏈接
本文內(nèi)容根據(jù)網(wǎng)絡資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉載請注明,如有侵權,聯(lián)系刪除。