一、簡介
1、概念
Pandas(Python Data Analysis Library)是一個(gè)基于 NumPy 的數(shù)據(jù)分析工具,專為解決數(shù)據(jù)分析任務(wù)而創(chuàng)建。它匯集了大量庫和一些標(biāo)準(zhǔn)的數(shù)據(jù)模型,可以更高效地操作大型數(shù)據(jù)集。
2、特點(diǎn)
- 數(shù)據(jù)結(jié)構(gòu): Pandas 提供了兩種主要的數(shù)據(jù)結(jié)構(gòu),即 Series 和 DataFrame,用于處理一維和二維數(shù)據(jù)。
- 標(biāo)簽化: 數(shù)據(jù)結(jié)構(gòu)帶有標(biāo)簽,可以通過標(biāo)簽進(jìn)行軸向操作,提高了數(shù)據(jù)操作的靈活性。
- 數(shù)據(jù)清洗: 提供了豐富的功能用于處理缺失值、重復(fù)項(xiàng)、異常值等,使數(shù)據(jù)更整潔。
- 數(shù)據(jù)操作: 支持各種數(shù)據(jù)操作,包括合并、連接、分組、聚合等,滿足多種數(shù)據(jù)分析需求。
- 時(shí)間序列: 強(qiáng)大的時(shí)間序列處理功能,方便處理時(shí)間相關(guān)的數(shù)據(jù)。
3、引用
pip install pandas
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
二、數(shù)據(jù)結(jié)構(gòu)
1、Series
- 基本屬性
values:返回底層的 NumPy 數(shù)組,包含 Series 中的數(shù)據(jù)。
index:返回索引對(duì)象,提供標(biāo)簽信息,用于標(biāo)識(shí)每個(gè)數(shù)據(jù)點(diǎn)。
dtype:返回?cái)?shù)據(jù)的數(shù)據(jù)類型,表示 Series 中存儲(chǔ)的元素類型。
shape:返回?cái)?shù)據(jù)的形狀,對(duì)于一維數(shù)據(jù),返回的是單元素元組。
size:返回?cái)?shù)據(jù)的元素個(gè)數(shù),表示 Series 中包含的數(shù)據(jù)點(diǎn)的數(shù)量。
nbytes:返回?cái)?shù)據(jù)的字節(jié)大小,即存儲(chǔ)數(shù)據(jù)所需的字節(jié)數(shù)。
ndim:返回?cái)?shù)據(jù)的維度,對(duì)于 Series 來說,始終為1。
name:返回或設(shè)置 Series 的名稱,可以用于標(biāo)識(shí) Series 對(duì)象的用途或含義。
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建一個(gè) Series 對(duì)象
s = pd.Series([1, 2, 3, 4, 5], name='my_series')
print(s.values) # [1 2 3 4 5]
print(s.index) # RangeIndex(start=0, stop=5, step=1)
print(s.dtype) # int64
print(s.shape) # (5,)
print(s.size) # 5
print(s.nbytes) # 40
print(s.ndim) # 1
print(s.name) # my_series
- 創(chuàng)建
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
import numpy as np # 導(dǎo)入 NumPy 庫并使用別名 np
# 從列表創(chuàng)建 Series
s1 = pd.Series([1, 2, 3, 4, 5])
print(s1)
# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
# dtype: int64
# 從字典創(chuàng)建 Series
s2 = pd.Series({'a': 1, 'b': 2, 'c': 3})
print(s2)
# a 1
# b 2
# c 3
# dtype: int64
# 從 Numpy 數(shù)組創(chuàng)建 Series
s3 = pd.Series(np.array([1, 2, 3, 4, 5]))
print(s3)
# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
# dtype: int32
# 從字典和標(biāo)簽列表創(chuàng)建 Series
s4 = pd.Series({'a': 1, 'b': 2, 'c': 3}, index=['a', 'b', 'c'])
print(s4)
# a 1
# b 2
# c 3
# dtype: int64
- 取值
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建一個(gè) Series 對(duì)象
s = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
# 通過索引取值
value = s['b']
print(value) # 2
# 通過切片取值
slice_values = s['a':'c']
print(slice_values)
# a 1
# b 2
# c 3
# dtype: int64
# 取第二行
row_value = s.iloc[1]
print(row_value) # 2
2、DataFrame
- 基本屬性
values:返回底層的 NumPy 數(shù)組,包含 DataFrame 中的數(shù)據(jù)。
columns:返回列名,表示 DataFrame 中每列的標(biāo)簽。
index:返回索引對(duì)象,提供標(biāo)簽信息,用于標(biāo)識(shí)每行數(shù)據(jù)。
shape:返回?cái)?shù)據(jù)的形狀,是一個(gè)元組,表示DataFrame的行數(shù)和列數(shù)。
dtypes:返回每列的數(shù)據(jù)類型,表示 DataFrame 中存儲(chǔ)的元素類型。
size:返回?cái)?shù)據(jù)的元素個(gè)數(shù),表示 DataFrame 中包含的數(shù)據(jù)點(diǎn)的總數(shù)量。
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建一個(gè) DataFrame 對(duì)象
data = {'name': ['Tom', 'Nick', 'John'], 'Age': [20, 21, 19]}
df = pd.DataFrame(data)
print(df.columns) # Index(['name', 'Age'], dtype='object')
print(df.index) # RangeIndex(start=0, stop=3, step=1)
print(df.values)
# [['Tom' 20]
# ['Nick' 21]
# ['John' 19]]
print(df.shape) # (3, 2)
print(df.dtypes)
# name object
# Age int64
# dtype: object
print(df.size) # 6
- 創(chuàng)建
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
import numpy as np # 導(dǎo)入 NumPy 庫并使用別名 np
# 創(chuàng)建一個(gè)字典
data = {'name': ['Tom', 'Nick', 'John', 'Tom'], 'Age': [20, 21, 19, 18]}
# 從字典創(chuàng)建 DataFrame
df = pd.DataFrame(data)
print(df)
# name Age
# 0 Tom 20
# 1 Nick 21
# 2 John 19
# 3 Tom 18
# 創(chuàng)建一個(gè)列表
data = [['Tom', 20], ['Nick', 21], ['John', 19], ['Tom', 18]]
# 從列表創(chuàng)建 DataFrame,指定列為'name'和'Age'
df = pd.DataFrame(data, columns=['name', 'Age'])
print(df)
# name Age
# 0 Tom 20
# 1 Nick 21
# 2 John 19
# 3 Tom 18
# 創(chuàng)建一個(gè)二維數(shù)組
data = np.array([['Tom', 20], ['Nick', 21], ['John', 19], ['Tom', 18]])
# 從二維數(shù)組創(chuàng)建 DataFrame,指定列為'name'和'Age'
df = pd.DataFrame(data, columns=['name', 'Age'])
print(df)
# name Age
# 0 Tom 20
# 1 Nick 21
# 2 John 19
# 3 Tom 18
# 創(chuàng)建一個(gè) DataFrame,然后使用該 DataFrame 創(chuàng)建另一個(gè) DataFrame
df1 = pd.DataFrame({'name': ['Tom', 'Nick', 'John'], 'Age': [20, 21, 19]})
df2 = pd.DataFrame(df1['name'], columns=['name']) # 使用 df1 的一個(gè)列創(chuàng)建新的 DataFrame
print(df2)
# name
# 0 Tom
# 1 Nick
# 2 John
# 添加一行
new_row = {'name': 'Alex', 'Age': 22}
# 使用 concat 方法將新行添加到 DataFrame,ignore_index=True 用于重置索引
df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
print(df)
# name Age
# 0 Tom 20
# 1 Nick 21
# 2 John 19
# 3 Tom 18
# 4 Alex 22
- 取值
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建一個(gè) DataFrame
data = {'Name': ['Tom', 'Nick', 'John', 'Peter'],'Age': [20, 21, 19, 18],'Score': [85, 80, 90, 88]}
df = pd.DataFrame(data)
# 通過列標(biāo)簽取值
# 選取單列
print(df['Name'])
# 0 Tom
# 1 Nick
# 2 John
# 3 Peter
# Name: Name, dtype: object
# 選取多列
print(df[['Name', 'Age']])
# Name Age
# 0 Tom 20
# 1 Nick 21
# 2 John 19
# 3 Peter 18
# 通過標(biāo)簽索引取值
# 設(shè)置行標(biāo)簽并選取行
df.index = ['Student1', 'Student2', 'Student3', 'Student4']
print(df.loc['Student1'])
# Name Tom
# Age 20
# Score 85
# Name: Student1, dtype: object
# 通過位置取值
# 選取第一行(索引為0)
print(df.iloc[0])
# Name Tom
# Age 20
# Score 85
# Name: Student1, dtype: object
# 使用布爾索引取值
# 選取年齡大于20的行
print(df[df['Age'] > 20])
# Name Age Score
# Student2 Nick 21 80
- 修改 index、columns
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
data = {'name': ['Tom', 'Nick', 'John'], 'Age': [20, 21, 19]}
df = pd.DataFrame(data)
print(df)
# name Age
# 0 Tom 20
# 1 Nick 21
# 2 John 19
df.index = ['name', 'Age', 'height']
df.columns = ['Name', 'Age']
print(df)
# Name Age
# name Tom 20
# Age Nick 21
# height John 19
- 篩選
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
import numpy as np # 導(dǎo)入 NumPy 庫并使用別名 np
# 創(chuàng)建一個(gè)字典
data = {'name': ['Tom', 'Nick', 'John', 'Tom'], 'Age': [20, 21, 19, 18]}
# 從字典創(chuàng)建 DataFrame
df = pd.DataFrame(data)
print(df)
# name Age
# 0 Tom 20
# 1 Nick 21
# 2 John 19
# 3 Tom 18
# 根據(jù)條件篩選數(shù)據(jù)
filtered_df = df[df['Age'] > 20]
print(filtered_df)
# name Age
# 1 Nick 21
三、常見操作
1、數(shù)據(jù)合并
- concat
用于沿著一條軸(通常是行軸)連接兩個(gè)或更多的對(duì)象。它不會(huì)改變軸標(biāo)簽。默認(rèn)情況下,concat 沿著行方向(axis=0)連接對(duì)象。
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建兩個(gè) DataFrame
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2'],
'C': ['C0', 'C1', 'C2'],
'D': ['D0', 'D1', 'D2']},
index=[0, 1, 2])
df2 = pd.DataFrame({'A': ['A3', 'A4', 'A5'],
'B': ['B3', 'B4', 'B5'],
'C': ['C3', 'C4', 'C5'],
'D': ['D3', 'D4', 'D5']},
index=[3, 4, 5])
result = pd.concat([df1, df2])
print(result)
# A B C D
# 0 A0 B0 C0 D0
# 1 A1 B1 C1 D1
# 2 A2 B2 C2 D2
# 3 A3 B3 C3 D3
# 4 A4 B4 C4 D4
# 5 A5 B5 C5 D5
- join
DataFrame 中的 join 方法用于將兩個(gè) DataFrame 連接在一起,連接是基于索引(行標(biāo)簽)進(jìn)行的。
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建兩個(gè) DataFrame
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2']},
index=[0, 1, 2])
df2 = pd.DataFrame({'C': ['C0', 'C1', 'C2'],
'D': ['D0', 'D1', 'D2']},
index=[0, 1, 2])
result = df1.join(df2, how='inner') # how='inner' 表示內(nèi)連接,即只保留兩個(gè) DataFrame 中都有數(shù)據(jù)的行
print(result)
# A B C D
# 0 A0 B0 C0 D0
# 1 A1 B1 C1 D1
# 2 A2 B2 C2 D2
- merge
用于將兩個(gè) DataFrame 沿著一個(gè)或多個(gè)鍵(可以是行或列標(biāo)簽)進(jìn)行連接,允許指定連接的鍵,可以進(jìn)行左連接、右連接或外連接。
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建兩個(gè) DataFrame
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2']},
index=[0, 1, 2])
df2 = pd.DataFrame({'C': ['C0', 'C1', 'C2'],
'D': ['D0', 'D1', 'D2']},
index=[0, 1, 3])
# left_index=True 表示進(jìn)行左連接,即保留 df1 中的所有行,右連接同理。
# 默認(rèn)情況下,兩個(gè) DataFrame 的索引都會(huì)被保留下來。
# 如果不想保留某個(gè) DataFrame 的索引,可以使用 how='inner' 或 how='outer' 進(jìn)行內(nèi)連接或外連接。
result = pd.merge(df1, df2, left_index=True, right_index=True)
print(result)
# A B C D
# 0 A0 B0 C0 D0
# 1 A1 B1 C1 D1
2、數(shù)據(jù)刪除
pandas.drop(labels=None, axis=0, index=None, columns=None, level=None, inpl
ace=False, errors='raise')
參數(shù)說明:
labels:要?jiǎng)h除的行或列的標(biāo)簽。
axis:刪除行還是列,0 或 ‘index’ 代表行,1 或 ‘columns’ 代表列。
index:要?jiǎng)h除的行的索引。
columns:要?jiǎng)h除的列的標(biāo)簽。
level:用于多層次索引(MultiIndex)的級(jí)別。
inplace:是否在原地修改 DataFrame。如果是 True,則直接在原 DataFrame 上進(jìn)行修改,否則返回一個(gè)新的 DataFrame。
errors:如果嘗試刪除不存在的標(biāo)簽會(huì)引發(fā)什么錯(cuò)誤,‘raise’ 表示引發(fā)錯(cuò)誤,‘ignore’ 表示忽略。
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建 DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
print(df)
# A B C
# 0 1 4 7
# 1 2 5 8
# 2 3 6 9
df.drop(columns='A', inplace=True)
print(df)
# B C
# 0 4 7
# 1 5 8
# 2 6 9
3、創(chuàng)建多層索引
使用 pd.MultiIndex.from_arrays() 方法創(chuàng)建多級(jí)索引對(duì)象。該方法接受兩個(gè)列表作為參數(shù),分別表示索引的級(jí)別。
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
index = pd.MultiIndex.from_arrays([['A', 'A', 'B', 'B'], [1, 2, 1, 2]], names=['letters', 'numbers'])
df = pd.DataFrame({'col1': [10, 20, 30, 40]}, index=index)
print(df)
# col1
# letters numbers
# A 1 10
# 2 20
# B 1 30
# 2 40
result = df.loc['A'] # 選擇第一級(jí)索引為 'A' 的數(shù)據(jù)
print(result)
# col1
# numbers
# 1 10
# 2 20
result = df.loc[('A', 2)] # 選擇第一級(jí)索引為 'A',第二級(jí)索引為 2 的數(shù)據(jù)
print(result)
# col1 20
# Name: (A, 2), dtype: int64
4、數(shù)據(jù)對(duì)齊
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建兩個(gè) Series 對(duì)象
s1 = pd.Series([1, 2, 3])
s2 = pd.Series([4, 5, 6])
# 算術(shù)運(yùn)算
add_result = s1 + s2
print(add_result)
# 0 5
# 1 7
# 2 9
# dtype: int64
sub_result = s1 - s2
print(sub_result)
# 0 -3
# 1 -3
# 2 -3
# dtype: int64
mul_result = s1 * s2
print(mul_result)
# 0 4
# 1 10
# 2 18
# dtype: int64
div_result = s1 / s2
print(div_result)
# 0 0.25
# 1 0.40
# 2 0.50
# dtype: float64
5、排序
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建一個(gè) DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 22],
'Score': [90, 85, 88]}
df = pd.DataFrame(data)
# 顯示原始 DataFrame
print(df)
# Name Age Score
# 0 Alice 25 90
# 1 Bob 30 85
# 2 Charlie 22 88
# 根據(jù) 'Score' 列的值進(jìn)行排序
df_sorted_by_score = df.sort_values(by='Score', ascending=False)
print(df_sorted_by_score)
# Name Age Score
# 0 Alice 25 90
# 2 Charlie 22 88
# 1 Bob 30 85
# 根據(jù)索引進(jìn)行排序
df_sorted_by_index = df.sort_index(ascending=False)
print(df_sorted_by_index)
# Name Age Score
# 2 Charlie 22 88
# 1 Bob 30 85
# 0 Alice 25 90
6、DataFrame 和 Series 之間的運(yùn)算
import pandas as pd # 導(dǎo)入 Pandas 庫并使用別名 pd
# 創(chuàng)建一個(gè) DataFrame 和一個(gè) Series
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
series = pd.Series([5, 6], index=['A', 'B'])
# 加法運(yùn)算
add_result = df + series
print(add_result)
# A B
# 0 6 9
# 1 7 10
# 減法運(yùn)算
subtract_result = df - series
print(subtract_result)
# A B
# 0 -4 -3
# 1 -3 -2
# 乘法運(yùn)算
multiply_result = df * series
print(multiply_result)
# A B
# 0 5 18
# 1 10 24
# 除法運(yùn)算
divide_result = df / series
print(divide_result)
# A B
# 0 0.2 0.500000
# 1 0.4 0.666667
四、應(yīng)用
爬取天氣數(shù)據(jù)并保存為 DataFrame 格式文章來源:http://www.zghlxwxcb.cn/news/detail-834879.html
import pandas as pd # 導(dǎo)入 pandas 庫,用別名 pd
import requests # 導(dǎo)入 requests 模塊,用于發(fā)送 HTTP 請(qǐng)求
from lxml import etree # 導(dǎo)入 lxml 中的 etree 模塊,用于處理和解析 XML 數(shù)據(jù)
# 定義目標(biāo)網(wǎng)址
url = 'https://weather.cma.cn/'
# 定義請(qǐng)求頭,模擬瀏覽器訪問
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
# 發(fā)送 HTTP GET 請(qǐng)求獲取頁面內(nèi)容
res = requests.get(url, headers=header)
# 將獲取的頁面內(nèi)容解碼成 UTF-8 格式
content = res.content.decode('utf-8')
# 使用 etree.HTML 解析 HTML 內(nèi)容
tree = etree.HTML(content)
# 從 HTML 樹中提取所有 id 為 "HOT" 的 div 下的 a 標(biāo)簽
a_s = tree.xpath('//div[@id="HOT"]/a')
# 創(chuàng)建一個(gè)空列表用于存儲(chǔ)提取的數(shù)據(jù)
lst = []
# 遍歷除第一個(gè)外的所有 a 標(biāo)簽
for a in a_s[1:]:
# 創(chuàng)建一個(gè)空字典用于存儲(chǔ)當(dāng)前城市的信息
dic = {}
# 提取當(dāng)前城市的排名信息,并去除首尾空格
dic['排名'] = a.xpath('./div[@class="rank"]/text()')[0].strip()
# 提取當(dāng)前城市的名稱信息,并去除首尾空格
dic['城市'] = a.xpath('./div[@class="sname"]/text()')[0].strip()
# 提取當(dāng)前城市所屬省份的信息,并去除首尾空格
dic['省份'] = a.xpath('./div[@class="pname"]/text()')[0].strip()
# 提取當(dāng)前城市的最高溫度信息,并去除首尾空格
dic['最高溫度'] = a.xpath('./div[@class="value"]/text()')[0].strip()
# 將當(dāng)前城市的信息字典添加到列表中
lst.append(dic)
# 打印最終提取的城市信息列表
print(lst)
# [{'排名': '1', '城市': '昌江', '省份': '海南', '最高溫度': '29.9℃'}, {'排名': '2', '城市': '景洪', '省份': '云南', '最高溫度': '29.7℃'}, {'排名': '3', '城市': '勐臘', '省份': '云南', '最高溫度': '29℃'}, {'排名': '4', '城市': '保亭', '省份': '海南', '最高溫度': '28.9℃'}, {'排名': '5', '城市': '樂東', '省份': '海南', '最高溫度': '28.9℃'}, {'排名': '6', '城市': '白沙', '省份': '海南', '最高溫度': '28.3℃'}, {'排名': '7', '城市': '巧家', '省份': '云南', '最高溫度': '28.2℃'}, {'排名': '8', '城市': '東川', '省份': '云南', '最高溫度': '28.1℃'}, {'排名': '9', '城市': '儋州', '省份': '海南', '最高溫度': '27.7℃'}, {'排名': '10', '城市': '番禺', '省份': '廣東', '最高溫度': '27.6℃'}]
# 使用提取的數(shù)據(jù)創(chuàng)建 DataFrame
df = pd.DataFrame(lst)
# 打印 DataFrame
print(df)
# 排名 城市 省份 最高溫度
# 0 1 昌江 海南 29.9℃
# 1 2 景洪 云南 29.7℃
# 2 3 勐臘 云南 29℃
# 3 4 保亭 海南 28.9℃
# 4 5 樂東 海南 28.9℃
# 5 6 白沙 海南 28.3℃
# 6 7 巧家 云南 28.2℃
# 7 8 東川 云南 28.1℃
# 8 9 儋州 海南 27.7℃
# 9 10 番禺 廣東 27.6℃
記錄學(xué)習(xí)過程,歡迎討論交流,尊重原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處~文章來源地址http://www.zghlxwxcb.cn/news/detail-834879.html
到了這里,關(guān)于數(shù)據(jù)分析 — Pandas 數(shù)據(jù)處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!