利用pandas處理Excel數(shù)據(jù)
新建一個excel表格(table1.csv)用于案例講解:

導庫
import pandas as pd
import numpy as np
讀取數(shù)據(jù)
df = pd.read_excel('table1.xlsx') # 相對路徑
# df = pd.read_excel(r'E:\Anaconda\hc\dataScience\table1.csv') # 絕對路徑
顯示數(shù)據(jù)
顯示數(shù)據(jù)的行與列數(shù)
df.shape
(6, 5)
顯示數(shù)據(jù)格式dtpyes
df.dtypes
Name object
Age int64
Sex int64
Class int64
Score float64
dtype: object
顯示列名
df.columns
Index(['Name', 'Age', 'Sex', 'Class', 'Score'], dtype='object')
顯示前數(shù)據(jù)前2行
df.head(2)

顯示數(shù)據(jù)后3行
df.tail(3)

顯示數(shù)據(jù)唯一值(unique函數(shù))
df['Score'].unique()
array([ 80., 90., 100., nan])
對第幾行數(shù)據(jù)不讀取
# 沒有讀取第2行
df1 = pd.read_excel('table1.csv',skiprows=[2] )

對缺失值進行識別
# 所有缺失值顯示為True
df.isnull()

清洗數(shù)據(jù)
刪除空值(dropna函數(shù))
df2 = df.dropna(how='any')

填充空值(fillna函數(shù))
df3 = df.fillna(value=0)

用均值對空值進行填充
df4 = df['Score'].fillna(df['Score'].mean())
0 80.0
1 90.0
2 100.0
3 90.0
4 88.0
5 80.0
Name: Score, dtype: float64
更改數(shù)據(jù)格式
df1['Score'].astype('int64')
0 80
1 90
2 100
3 90
5 80
Name: Score, dtype: int64
(注:如果存在空值,更改數(shù)據(jù)格式會報錯?。?/p>
更改列名
df5 = df.rename(columns={'Score': 'score'})

對列表內(nèi)的值進行替換(replace函數(shù))
df6 = df['Name'].replace('Bob', 'bob')
0 Tom
1 Jack
2 Alan
3 Tony
4 Tim
5 bob
Name: Name, dtype: object
數(shù)據(jù)預處理
對數(shù)據(jù)進行排序
df.sort_values(by=['Score'])

(注:默認升序,且空值在后面)
數(shù)據(jù)分組
①單一條件分組
# 如果Score列的值>=85,Score列顯示high,否則顯示low
# group列為增加列
df['group'] = np.where(df['Score'] > 85,'high','low')

②多個條件分組
# 利用loc函數(shù),進行多列查詢
# sign為增加列
df.loc[(df['Sex'] == 1) & (df['Age']>= 19), 'sign']=1

數(shù)據(jù)提取
按標簽提取(loc函數(shù))
df.loc[0:3]

按位置進行提?。╥loc函數(shù))
①按區(qū)域提取
df.iloc[:4, :5]

②按位置提取
#[0, 2, 5] 代表指定的行,[0, 1, 5] 代表指定的列
df.iloc[[0, 2, 5],[0, 1, 5]]

按條件提?。╥sin與loc函數(shù))
①用isin函數(shù)進行判斷
# 判斷Sex是否為1
df['Sex'].isin([1])
0 True
1 True
2 True
3 False
4 False
5 True
Name: Sex, dtype: bool

②用loc函數(shù)進行判斷
# Sex為1,分數(shù)大于85
df1.loc[(df1['Sex'] == 1) & (df1['Score'] > '85'), ['Name','Age','Class']]
③先判斷結果,將結果為True的提取
# 先判斷Score列里是否包含80和90,然后將復合條件的數(shù)據(jù)提取出來。
df.loc[df['Score'].isin(['80','90'])]

作者:AI阿聰
版權聲明:本文為博主原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權協(xié)議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/weixin_40431584/article/details/103993722
微信掃碼關注,了解更多內(nèi)容
評論
圖片
表情
