Pandas是Python中用于數(shù)據(jù)處理和分析的強(qiáng)大庫。這篇文章將深入探討Pandas庫的高級(jí)功能:數(shù)據(jù)透視表和字符串操作。
一、數(shù)據(jù)透視表
數(shù)據(jù)透視表是一種常見的數(shù)據(jù)匯總工具,常用于電子表格程序和某些數(shù)據(jù)庫。Pandas提供了創(chuàng)建數(shù)據(jù)透視表的功能吓笙,這使得數(shù)據(jù)分析更加靈活和直觀。
1. 創(chuàng)建數(shù)據(jù)透視表
Pandas的pivot_table()
函數(shù)可以輕松地創(chuàng)建數(shù)據(jù)透視表巾腕。我們需要指定以下參數(shù):values
(要聚合的列名)面睛,index
(在透視表的行中要分組的列名),columns
(在透視表的列中要分組的列名)尊搬,aggfunc
(用于聚合的函數(shù))叁鉴。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'A': ['one', 'one', 'two', 'three'] * 3,
'B': ['A', 'B', 'C'] * 4,
'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D': np.random.randn(12),
'E': np.random.randn(12)
})
# 創(chuàng)建數(shù)據(jù)透視表
pivot_table = df.pivot_table(values='D', index=['A', 'B'], columns=['C'], aggfunc=np.sum)
print(pivot_table)
2. 查詢數(shù)據(jù)透視表
你可以像查詢普通的DataFrame那樣查詢數(shù)據(jù)透視表。
# 查詢數(shù)據(jù)透視表
print(pivot_table.loc['one']) # 查詢行索引為'one'的數(shù)據(jù)
print(pivot_table['foo']) # 查詢列索引為'foo'的數(shù)據(jù)
二佛寿、字符串操作
Pandas提供了一系列的字符串處理方法幌墓,在str
屬性中集成了這些方法,這使得在DataFrame和Series中的字符串操作更加方便冀泻。
1. 字符串基本操作
Pandas支持大部分Python內(nèi)置的字符串方法常侣。
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
print(s.str.lower()) # 將字符串轉(zhuǎn)化為小寫
2. 使用正則表達(dá)式
Pandas的字符串方法能夠接受正則表達(dá)式,這使得字符串操作更加強(qiáng)大弹渔。例如胳施,我們可以使用正則表達(dá)式,配合replace()
函數(shù)替換字符串中的字符肢专。
s = pd.Series(['a', 'a|b', np.nan, 'a|c'])
print(s.str.replace('a|b', 'new', regex=True)) # 使用正則表達(dá)式替換字符串
通過以上這兩個(gè)方面的深入探討舞肆,我們可以看到Pandas在高級(jí)數(shù)據(jù)處理方面的強(qiáng)大能力。使用數(shù)據(jù)透視表和字符串操作博杖,可以讓我們更有效地進(jìn)行數(shù)據(jù)處理椿胯。
三、向量化字符串操作
Pandas庫在str
屬性下提供了一系列字符串處理方法剃根,這些方法可以更方便地進(jìn)行向量化字符串操作哩盲,實(shí)現(xiàn)在整個(gè)Series或DataFrame中的字符串處理。
1. 向量化操作的基本方法
向量化操作的基本方法主要包括:大小寫轉(zhuǎn)換、長(zhǎng)度計(jì)算种冬、分割镣丑、替換等。
s = pd.Series(['Pandas', 'Is', 'An', 'Excellent', 'Library'])
print(s.str.lower()) # 轉(zhuǎn)為小寫
print(s.str.len()) # 計(jì)算長(zhǎng)度
print(s.str.split()) # 分割字符串
print(s.str.replace('A', 'a')) # 替換字符
2. 使用正則表達(dá)式的向量化操作
Pandas的字符串方法支持正則表達(dá)式娱两,能實(shí)現(xiàn)更復(fù)雜的字符串操作。
s = pd.Series(['Pandas', 'Is', 'Not only', 'An', 'Excellent', 'Library'])
print(s.str.contains('An')) # 檢查字符串是否包含"An"
print(s.str.extract('([A-Za-z]+)')) # 提取匹配正則表達(dá)式的部分
四金吗、應(yīng)用函數(shù)
Pandas也支持應(yīng)用自定義函數(shù)或者lambda函數(shù)到Series或DataFrame的元素十兢。
1. 對(duì)Series應(yīng)用函數(shù)
s = pd.Series([20, 21, 12], index=['London', 'New York', 'Helsinki'])
# 使用apply()函數(shù)
print(s.apply(lambda x: x**2)) # 對(duì)Series的每個(gè)元素求平方
2. 對(duì)DataFrame應(yīng)用函數(shù)
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [10, 20, 30],
'C': [7, 8, 9]
})
# 使用applymap()函數(shù)
print(df.applymap(lambda x: x**2)) # 對(duì)DataFrame的每個(gè)元素求平方
通過上述內(nèi)容,我們對(duì)Pandas庫中的字符串操作和數(shù)據(jù)透視表有了更深入的了解摇庙,希望這能在你的數(shù)據(jù)處理和分析工作中起到幫助旱物。