Pandas數(shù)據(jù)分析常用函數(shù)的使用
Pandas是數(shù)據(jù)處理和分析過程中常用的Python包,提供了大量能使我們快速便捷地處理數(shù)據(jù)的函數(shù)和方法,在此主要整理數(shù)據(jù)分析過程pandas包常用函數(shù),以便查詢。更多函數(shù)學習詳見padans官網(wǎng)
一、數(shù)據(jù)導入導出
pandas提供了一些用于將表格型數(shù)據(jù)讀取為DataFrame對象函數(shù),如read_csv,read_table。輸入pd.read后,按Tab鍵,系統(tǒng)將把以read開頭的函數(shù)和模塊都列出來,根據(jù)需要讀取的文件類型選取。
#包的安裝導入 import pandas as pd #查詢幫助文檔 pd.read_csv? #數(shù)據(jù)載入(僅羅列一部分常用參數(shù)) df = pd.read_csv( ? ? ?filePath, #路徑? ? ? ?sep=',', ?#分隔符 ? ? ?encoding='UTF-8', #用于unicode的文本編碼格式,如GBK,UTF-8 ? ? ?engine='python', ? ? ?header = None, #第一行不作為列名 ? ? ?names= [['col1','col2']], #字段名設置 ? ? ?index_col=None,? ? ? ?skiprows=None, #跳過行None ? ? ?error_bad_lines=False #錯誤行忽略 ? ? ) # 數(shù)據(jù)導出 df.to_csv(filePath, ? ? ? ? ? ?sep = ',', ? ? ? ? ? ?index = False)
二、數(shù)據(jù)加工處理
1)重復值處理
# Pandas提供了duplicated、Index.duplicated、drop_duplicates函數(shù)來標記及刪除重復記錄
#找出重復行位置
dIndex = df.duplicated()
#根據(jù)某些列找出重復位置
dIndex = df.duplicated('id')
dIndex = df.duplicated(['id', 'key'])
#根據(jù)返回值提取重復數(shù)據(jù)
df[dIndex]
#刪除重復行
newdf = df.drop_duplicated()
#去掉重復數(shù)據(jù)
newdf = df.drop_duplicated(keep = False)
#根據(jù)'key'字段去重,并保留重復key字段第一個
##subset:指定的標簽或標簽序列,僅刪除這些列重復值,默認情況為所有列
##keep:確定要保留的重復值:first(保留第一次出現(xiàn)的重復值,默認)last(保留最后一次出現(xiàn)的重復值)False(刪除所有重復值)
newdf = df.drop_duplicated(subset = ['key'],keep = 'first')2)缺失值處理
# 輸出某列是否有為空值
print(df.isnull().any(axis = 0))
# 獲取空值所在的行
df[df.isnull().any(axis = 1)]
# 空值填充
df.fillna('未知')
# 刪除空值
newDF = dropna(axis="columns",how="all",inplace=False) #how可選有any和all,any表示只要有空值出現(xiàn)就刪除,all表示全部為空值才刪除,inplace表示是否替換掉原本數(shù)據(jù)
3)空格處理
newName = df['name'].str.lstrip() newName = df['name'].str.rstrip() newName = df['name'].str.strip()
4)字段拆分
newDF = df['name'].str.split(' ', 1, True)
5)篩選數(shù)據(jù)
#單條件
df[df.comments>10000]
#多條件
df[df.comments.between(1000, 10000)]
#過濾空值所在行
df[pandas.isnull(df.title)]
#根據(jù)關鍵字過濾
df[df.title.str.contains('臺電', na=False)]
#~為取反
df[~df.title.str.contains('臺電', na=False)]
#組合邏輯條件
df[(df.comments>=1000) & (df.comments<=10000)]
6)隨機抽樣
#設置隨機種子 numpy.random.seed(seed=2) #按照個數(shù)抽樣 data.sample(n=10) #按照百分比抽樣 data.sample(frac=0.02) #是否可放回抽樣, #replace=True,可放回, #replace=False,不可放回 data.sample(n=10, replace=True)
7)數(shù)據(jù)匹配
items = pandas.read_csv(
'D:\\PDA\\4.12\\data1.csv',
sep='|',
names=['id', 'comments', 'title']
)
prices = pandas.read_csv(
'D:\\PDA\\4.12\\data2.csv',
sep='|',
names=['id', 'oldPrice', 'nowPrice']
)
#默認只是保留連接上的部分
itemPrices = pd.merge(
items,
prices,
left_on='id',
right_on='id',
how = 'left'
)
#how:連接方式,有inner、left、right、outer,默認為inner;8)數(shù)據(jù)合并
data = pd.concat([data1, data2, data3])
9)時間處理
data['時間'] = pandas.to_datetime(
data.注冊時間,
format='%Y/%m/%d'
)
data['格式化時間'] = data.時間.dt.strftime('%Y-%m-%d')
data['時間.年'] = data['時間'].dt.year
data['時間.月'] = data['時間'].dt.month
data['時間.周'] = data['時間'].dt.weekday
data['時間.日'] = data['時間'].dt.day
data['時間.時'] = data['時間'].dt.hour
data['時間.分'] = data['時間'].dt.minute
data['時間.秒'] = data['時間'].dt.second
10)數(shù)據(jù)標準化
data['scale'] = round(
(
data.score-data.score.min()
)/(
data.score.max()-data.score.min()
)
, 2
)
11)修改列名和索引
#將id列設為索引
df = df.set_index('id')
12)排序
#選定列排序 df.sort_values(by=['age', 'gender'], ascending=[False, True], inplace=True, ignore_index=True)
三、列表格式設置
pd.set_option('display.max_rows',xxx) # 最大行數(shù)
pd.set_option('display.min_rows',xxx) # 最小顯示行數(shù)
pd.set_option('display.max_columns',xxx) # 最大顯示列數(shù)
pd.set_option ('display.max_colwidth',xxx) #最大列字符數(shù)
pd.set_option( 'display.precision',2) # 浮點型精度
pd.set_option('display.float_format','{:,}'.format) #逗號分隔數(shù)字
pd.set_option('display.float_format', ?'{:,.2f}'.format) #設置浮點精度
pd.set_option('display.float_format', '{:.2f}%'.format) #百分號格式化
pd.set_option('plotting.backend', 'altair') # 更改后端繪圖方式
pd.set_option('display.max_info_columns', 200) # info輸出最大列數(shù)
pd.set_option('display.max_info_rows', 5) # info計數(shù)null時的閾值
pd.describe_option() #展示所有設置和描述
pd.reset_option('all') #重置所有設置選項到此這篇關于Pandas數(shù)據(jù)分析常用函數(shù)的使用的文章就介紹到這了,更多相關Pandas數(shù)據(jù)分析常用函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python基礎教程之Pandas數(shù)據(jù)分析庫詳解
- Python數(shù)據(jù)分析pandas之布爾索引使用詳解
- Python+pandas數(shù)據(jù)分析實踐總結
- Python實踐之使用Pandas進行數(shù)據(jù)分析
- Python?第三方庫?Pandas?數(shù)據(jù)分析教程
- Python利用Pandas進行數(shù)據(jù)分析的方法詳解
- Pandas數(shù)據(jù)分析-pandas數(shù)據(jù)框的多層索引
- Pandas數(shù)據(jù)分析之pandas數(shù)據(jù)透視表和交叉表
- python pandas模塊進行數(shù)據(jù)分析
相關文章
python使用兩種發(fā)郵件的方式smtp和outlook示例
本篇文章主要介紹了python使用兩種發(fā)郵件的方式smtp和outlook示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-06-06
python curl2pyreqs 生成接口腳本實戰(zhàn)教程
這篇文章主要介紹了python curl2pyreqs 生成接口腳本實戰(zhàn)教程,首先下載 curl2pyreqs 庫,打開調試模式,在Network這里獲取接口的cURL,需要的朋友可以參考下2023-10-10
python深度學習tensorflow實例數(shù)據(jù)下載與讀取
這篇文章主要為大家介紹了python深度學習tensorflow實例數(shù)據(jù)下載與讀取示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
PyCharm添加Anaconda中的虛擬環(huán)境Python解釋器出現(xiàn)Conda?executable?is?not
這篇文章主要給大家介紹了關于PyCharm添加Anaconda中的虛擬環(huán)境Python解釋器出現(xiàn)Conda?executable?is?not?found錯誤的解決辦法,文中通過圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2023-02-02

