當前位置:編程學習大全網 - 源碼下載 - Python其實很簡單 第十九章 Pandas之Series與DataFrame

Python其實很簡單 第十九章 Pandas之Series與DataFrame

19.1安裝Anaconda

Anaconda是Python的壹個開源發行版本,它預裝了豐富的第三方庫,而且主要面向科學計算和數據分析,使用起來要比原版的Python更省時省力。

Anaconda官方下載網址為:https://www.continuum.io/downloads。下載和安裝的方法很簡單,若有問題可以在網上搜索相關內容學習解決。

安裝Anaconda之後,就會發現在Anaconda目錄下同時安裝了Jupyter Notebook、Spyder等工具,我們接下來主要使用Spyder進行開發。關於Spyder的使用方法非常簡單,大家也可以去網上搜索學習。

雖然Anaconda已經預裝了很多常用的包,但有時我們也需要自己安裝壹些包。可以在開始菜單中選擇“Anaconda Anaconda Prompt”命令,在命令行輸入conda install ( 代表包名)即可安裝,也可以輸入pip install 。

19.2數據分析包Pandas

Pandas是Python的壹個數據分析包,Anaconda安裝時已經附帶安裝了Pandas包。

Pandas數據結構有三種:Series(壹維數組)、DataFrame(二維數組)和Panel(三維數組),其中最常用的是前兩種數據結構。

19.2.1 Series

Series(序列)用於存儲壹行或壹列數據,以及與之相關的索引的集合。

語法格式如下:

Series([數據1,數據2,......], index=[索引1,索引2,......])

例:

from pandas import Series

s=Series(['張三','李四','王五'],index=[1,2,3])

print(s)

輸出結果如下:

1 張三

2 李四

3 王五

dtype: object

上面建立序列時指定了索引,若不指定,則默認的索引值從0開始。如下:

s=Series(['張三','李四','王五'])

輸出結果為:

0 張三

1 李四

2 王五

dtype: object

索引值也可以為字符串。如下:

from pandas import Series

s=Series(['張三','李四','王五'],index=['A','B','C'])

print(s)

輸出結果為:

A 張三

B 李四

C 王五

dtype: object

1、訪問序列

(1)可以通過索引訪問序列,如:

from pandas import Series

s=Series(['張三','李四','王五'])

print(s)

print(s[0])

print(s[1:])

運行結果如下:

0 張三

1 李四

2 王五

dtype: object #print(s)輸出

張三 #print(s[0])輸出

1 李四

2 王五

dtype: object #print(s[1:])輸出

(2)通過值獲取索引值

from pandas import Series

s=Series(['張三','李四','王五'],index=['A','B','C'])

print(s.index[s.values=='李四'])

運行結果:

Index(['B'], dtype='object')

(3)判斷值是否存在

from pandas import Series

s=Series(['張三','李四','王五'],index=['A','B','C'])

f='李四' in s.values

print(f)

運行結果:

True

(4)定位獲取

from pandas import Series

s=Series(['張三','李四','王五','孫六'],index=['A','B','C','D'])

print(s[[0,2,1]])

運行結果:

A 張三

C 王五

B 李四

dtype: object

2、修改序列

(1)追加序列,如:

from pandas import Series

s=Series(['張三','李四','王五'],index=['A','B','C'])

s1=Series(['孫六'],index=['D'])

s=s.append(s1)

print(s)

運行結果:

A 張三

B 李四

C 王五

D 孫六

dtype: object

(2)修改序列的值

from pandas import Series

s=Series(['張三','李四','王五','孫六'],index=['A','B','C','D'])

s[1]='李飛'

print(s)

運行結果:

A 張三

B 李飛

C 王五

D 孫六

dtype: object

不知道索引,僅知道要修改的值,也可通過值查找到索引後,再修改序列的值。如:

s[s.index[s.values=='李四']]='李飛'

這樣也可以將“李四”修改為“李飛。

(3)修改索引

from pandas import Series

s=Series(['張三','李四','王五','孫六'],index=['A','B','C','D'])

s.index=[0,1,2,3]

print(s)

運行結果:

0 張三

1 李四

2 王五

3 孫六

dtype: object

(4)刪除元素

from pandas import Series

s=Series(['張三','李四','王五','孫六'],index=['A','B','C','D'])

s=s.drop('A')

print(s)

運行結果:

B 李四

C 王五

D 孫六

dtype: object

(5)重新排序

可以按照索引排序,使用sort_index(ascending=True)方法對index進行排序操作。

from pandas import Series

s=Series(['張三','李四','王五','孫六'],index=['A','B','C','D'])

s=s.sort_index(ascending=False) # ascending=False表示按降序排列

print(s)

運行結果:

D 孫六

C 王五

B 李四

A 張三

dtype: object

(6)重置索引

重置索引可以使用reindex()。如果index列表中的元素多於序列的值,可用fill_value=0這樣的語句填充。

s=s.reindex(['D','C','B','A'])

如果index列表中的元素多於序列的值,可用fill_value=0這樣的語句填充。

s=s.reindex(['D','C','B','A'], fill_value=0)

19.2.2 DataFrame

DataFrame(數據框架)用於存儲多行和多列的數據集合。它是Series的容器,類似於Excel中二維表格。

定義壹個DataFrame的語法格式如下:

df=DataFrame({列名1 : 序列1,列名2 : 序列2,.......列名n : 序列n}, index=序列 )

例如,有如下二維表:

姓名

性別

年齡

張三

18

李四

19

王五

17

保存到DataFrame中可以用如下方法:

from pandas import Series

from pandas import DataFrame

name=Series(['張三','李四','王五'])

sex=Series(['男','女','男'])

age=Series([18,19,17])

df=DataFrame({'姓名':name,'性別':sex,'年齡':age})

print(df)

運行結果:

姓名 性別 年齡

0 張三 男 18

1 李四 女 19

2 王五 男 17

從上例可以看出,雖然我們省缺了索引,但系統自動添加了從0開始的索引值。

19.3 DataFrame的基本操作

1、訪問方式

(1)獲取行

print(df[1:2]) # 獲取第1行的值

輸出結果:

姓名 性別 年齡

1 李四 女 19

print(df[1:3]) #獲取第1行到第2行的值

輸出結果:

姓名 性別 年齡

1 李四 女 19

2 王五 男 17

(2)獲取列

print(df['姓名']) #獲取“姓名”列的值

輸出結果:

0 張三

1 李四

2 王五

Name: 姓名, dtype: object

另壹種方法:

print(df[df.columns[0:1]]) #先按照索引號獲取列名,再按照列名讀取

輸出結果和上面的方法完全壹致。

還有壹種情況,是獲取唯壹值,即將列內的重復值中多余的刪除,僅留下互不相同的值。所用的到方法是unique()。

sex1=Series(df['性別'].unique())

print(sex1)

輸出結果:

0 男

1 女

dtype: object

(3)獲取指定位置的值

print(df.at[1,'姓名']) # 格式為變量名.at[行號,列名]

輸出結果:

李四

(4)獲取塊的值

print(df.iloc[0:2,1:3]) # 格式為變量名.iloc[行號1:行號2, 列號1:列號2]

輸出結果:

性別 年齡

0 男 18

1 女 19

print(df.iloc[:,1:2]) #獲取“性別”列的值

運行結果:

性別

0 男

1 女

2 男

2、修改、刪除、增加行和列

(1)修改列名

print(df.columns)

df.columns=['name','sex','age']

print(df.columns)

輸出結果:

Index(['姓名', '性別', '年齡'], dtype='object')

Index(['name', 'sex', 'age'], dtype='object')

可見,列名已經由“姓名、性別、年齡”修改為“age、sex、age”了。但這種修改必須把全部列名都壹壹列舉,不能有遺漏,否則就會出錯。如:

df.columns=['name','sex']

此時會報錯:ValueError: Length mismatch: Expected axis has 3 elements, new values have 2 elements。

(2)修改行索引

df.index=[1,2,3]

(3)刪除行

df.drop(1,axis=0) # axis=0表示行軸,也可以省略

(4)刪除列

df.drop(‘性別’,axis=1) # axis=0表示列軸

也可以使用另壹種方法:

del df['性別']

(5)增加列

df['電話']=['1111111','2222222','3333333']

print(df)

運行結果:

姓名 性別 年齡 電話

0 張三 男 18 1111111

1 李四 女 19 2222222

2 王五 男 17 3333333

(6)增加行

df.loc[len(df)]=['孫六','男','20']

(7)追加

from pandas import Series

from pandas import DataFrame

name=Series(['張三','李四','王五'])

sex=Series(['男','女','男'])

age=Series([18,19,17])

df=DataFrame({'姓名':name,'性別':sex,'年齡':age}) # 建立DataFrame,變量名為df

name1=Series(['孫六','候七'])

sex1=Series(['男','女'])

age1=Series([19,17])

df1=DataFrame({'姓名':name1,'性別':sex1,'年齡':age1})

# 建立DataFrame,變量名為df1

df=df.append(df1,ignore_index=True)

# 將對df1追加到df後面,參數ignore_index=True表示重新索引

print(df)

運行結果:

姓名 性別 年齡

0 張三 男 18

1 李四 女 19

2 王五 男 17

3 孫六 男 19

4 候七 女 17

  • 上一篇:如何更改dns設置如何更改dns設置手機
  • 下一篇:比特幣的來源是什麽
  • copyright 2024編程學習大全網