目錄
- 前言
- 1.資料集成
- 1.1 concat資料串聯
- 1.2 插入
- 1.3 Join SQL風格合并
- 2.資料清洗
- 2.1 重復資料過濾
- 2.2 空資料過濾
- 2.3 指定行或者列進行洗掉
- 2.4 例外值
- 3.資料轉換
- 3.1 軸和元素替換
- 3.1.1 軸的替換
- 3.1.2 元素的替換
- 3.2 map Series元素改變
- 3.3 apply元素改變,既支持 Series也支持 DataFrame
- 3.3.1 apply簡單介紹
- 3.3.2 apply應用
- 3.3.3 applymap應用
- 3.4 transform變形金剛
- 3.5 重排隨機抽樣啞變數
- 3.5.1 重拍資料
- 3.5.2 隨機抽樣
- 3.5.3 啞變數
- 4.訓練場
- 4.1 知識點概述
- 4.1.1 字串替換
- 4.1.2 報錯演示
- 4.1.3 報錯修復
- 4.2 體測成績的部分轉換
- 4.2.1 男生1000米跑成績轉換
- 4.2.2 男生1000米跑成績轉換并賦值
- 4.3 體測成績評分表資料轉換
- 4.4 男生體測分數成績轉換
- 4.4.1 男生1000米跑成績分數轉換
- 4.4.2 男生1000米跑成績分數轉換并賦值
- 4.4.3 批量轉換男生速度類成績分數
- 4.4.4 批量轉換男生力量型成績分數并保存
- 4.5 女生體測成績分數轉換
- 4.6 保存成績
前言
本文其實屬于:Python的進階之道【AIoT階段一】的一部分內容,本篇把這部分內容單獨截取出來,方便大家的觀看,本文介紹 pandas 高級,讀本文之前建議先修:pandas 入門,后續還會發出一篇 pandas 進階供讀者進行進一步的學習了解,
1.資料集成
🚩pandas 提供了多種將 Series、DataFrame 物件組合在一起的功能
1.1 concat資料串聯
🚩使用 concat 可以把資料進行合并,分別用 axis = 0 代表行合并,axis = 1 代表列合并
import pandas as pd
import numpy as np
# df1 看做是一班的考試成績
df1 = pd.DataFrame(data = np.random.randint(0, 150, size = (10, 3)),# 計算機科目的考試成績
index = list('ABCDEFGHIJ'), # 行標簽,用戶
columns = ['Python', 'Tensorflow', 'Keras']) # 考試科目
# df2 看做是二班的考試成績
df2 = pd.DataFrame(data = np.random.randint(0, 150, size = (10,3)),# 計算機科目的考試成績
index = list('KLMNOPQRST'),# 行標簽,用戶
columns = ['Python', 'Tensorflow', 'Keras']) # 考試科目
# df3 新增兩門考試科目(一班)
df3 = pd.DataFrame(data = np.random.randint(0, 150, size = (10,2)),
index = list('ABCDEFGHIJ'),
columns = ['PyTorch', 'Paddle'])
display(df1, df2, df3)
# 一班二班考試成績合并
# axis = 0 表示進行(xing)行(hang)合并, 即行增加
display(pd.concat([df1, df2], axis = 0))
# 一班科目增加,合并科目
# axis = 1 表示進行列合并,即列增加
display(pd.concat([df1, df3], axis = 1))

1.2 插入
🚩使用 insert 可以在任意位置進行插入
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 151, size = (10, 3)),
index = list('ABCDEFGHIJ'),
columns = ['Python', 'Keras', 'Tensorflow'])
display(df)
# 我們在 Keras 和 TensorFlow 中間插入一行 Math,分數均為150
df.insert(loc = 2, column = 'Math', value = 150)
# loc = 0 代表 Python, loc = 1 代表 Pytorch,以此類推
# 在 Python 后面插入一列 English
'''
獲取列索引
df.columns 運行結果:Index(['Python', 'Pytorch', 'Math', 'Keras', 'Tensorflow'],
dtype='object')
把列索引轉換為串列
list(df.columns) 運行結果:['Python', 'Pytorch', 'Math', 'Keras', 'Tensorflow']
呼叫index函式,獲取串列中特定欄位的位置
list(df.columns).index('Python') 運行結果:0
'''
# +1 表示在該位置后
index = list(df.columns).index('Python') + 1
df.insert(loc = index, column = 'English', value = np.random.randint(0, 151, size = 10))
display(df)

1.3 Join SQL風格合并
🚩資料集的合并(merge)或連接(join)運算是通過一個或者多個鍵將資料鏈接起來的,這些運算是關系型資料庫的核心操作,pandas的merge函式是資料集進行join運算的主要切入點,
先來創建資料:
import pandas as pd
import numpy as np
# 記錄的是name和weight
df1 = pd.DataFrame(data = {'name':['辰chen', '嬌妹兒', '梟哥', '晶姐'],
'weight':[65, 60, 70, 50]})
# 記錄的是name和height
df2 = pd.DataFrame(data = {'name':['辰chen', '嬌妹兒', '梟哥', '黑貓警長'],
'height':[176, 184, 178, 166]})
# 記錄的是名字和height
df3 = pd.DataFrame(data = {'名字':['辰chen', '嬌妹兒', '梟哥', '黑貓警長'],
'height':[176, 184, 178, 166]})
display(df1, df2, df3)

利用 merge 對資料進行合并:
# df1, df2 進行合并
display(pd.merge(df1, df2)) # merge:根據共同的屬性進行合并
# 共同的屬性是name,共同擁有的是:辰chen, 嬌妹兒, 梟哥

df1 和 df3 是不能直接進行合并的:
# df1, df3 進行合并
display(pd.merge(df1, df3))

當然啦,我們 pandas 是十分強大滴,按照如下代碼可以進行合并:
# df1, df3 進行合并
# 指定了合并時, 根據哪一列進行合并
display(pd.merge(df1, df3, left_on = 'name', right_on = '名字'))

創建 10 名同學,計算每個人的平均分,并合并:
創建資料:
df4 = pd.DataFrame(data = np.random.randint(0, 151, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns = ['Python', 'Keras', 'Tensorflow'])
display(df4)

計算平均分:
df4.mean()

我們要計算的不是列的平均分,而是每位同學的平均分:axis = 1:
# 每個人的各科平均分, Series
df4.mean(axis = 1)

資料看起來不舒服,我們可以使用之前講過的 round(1) 去保留一位小數:
# 每個人的各科平均分, Series
df4.mean(axis = 1).round(1)

看著是不是不是很舒服?我們可以把它變成 DataFrame
# 每個人的各科平均分, Series
t = df4.mean(axis = 1).round(1)
# 轉為 DataFrame
df5 = pd.DataFrame(t, columns = ['平均分'])
df5

將 df4 和 df5 使用 merge 進行合并
# 將 df4 和 df5 使用 merge 進行合并
# df4 和 df5 沒有共同的一列屬性值相同,擔有相同的行索引
pd.merge(df4, df5, left_index = True, # 左邊使用行索引
right_index = True) # 右邊使用行索引

上述代碼同樣可以用 concat 和 insert 實作:
pd.concat([df4, df5], axis = 1)

df4.insert(loc = 3, column = '平均分', value = df5)
df4

2.資料清洗
🚩所謂資料清洗,其實就是把重復的資料,或者是空資料,例外資料進行一些操作,比如替換,填充,洗掉等操作,關于例外值的定義需要根據實際情況去自行規定,
2.1 重復資料過濾
import numpy as np
import pandas as pd
df = pd.DataFrame(data = {'color':['red', 'blue', 'red', 'green', 'blue', None, 'red'],
'price':[10, 20, 10, 15, 20, 0, np.NaN]})
display(df)
# 重復資料過濾
df.duplicated() # 判斷是否存在重復資料
df.drop_duplicates() # 洗掉重復資料

2.2 空資料過濾
None 和 NaN 都表示空資料,計算時沒有區別
None 是 Python 的資料型別
NaN 是 Numpy 的資料型別
import numpy as np
import pandas as pd
df = pd.DataFrame(data = {'color':['red', 'blue', 'red', 'green', 'blue', None, 'red'],
'price':[10, 20, 10, 15, 20, 0, np.NaN]})
display(df)
# 空資料處理
# 比如 df 中的 color:None,price:NaN 就是空資料
display(df.isnull()) # 判斷是否存在空資料,存在回傳True,否則回傳False
display(df.dropna()) # 洗掉空資料
df.fillna(1024) # 填充空資料:空資料全變為1024

2.3 指定行或者列進行洗掉
del df['color'] # 直接洗掉某列
df

# drop 洗掉,原資料無變化
# 洗掉指定列
display(df.drop(labels = ['price'], axis = 1))
display(df)
# 洗掉指定行
display(df.drop(labels = [0, 1, 3], axis = 0))
display(df)

當然,我們也可以設定使得在原資料上直接進行修改:
# inplace 替換:洗掉原來資料并替換給原資料
# 說白了就是洗掉資料的意思
df.drop(labels = [0, 1, 3], axis = 0, inplace = True)
df

2.4 例外值
🚩對于一個正態分布的資料,我們認定 > 3 σ >3\sigma >3σ 就是例外值, σ \sigma σ表示標準差
# 正態分布資料
df = pd.DataFrame(data = np.random.randn(10000, 3))
cnt = df.abs() > 3 * df.std() # df.std() 就是標準差
# 取出第一列是例外的資料
cnt_0 = cnt[0]
display(df[cnt_0])
# 獲取每一列是例外的資料
cnt_1 = cnt[1]
cnt_2 = cnt[2]
cnt = cnt_0 | cnt_1 | cnt_2
df[cnt]

還有一種比較簡單的方式取出例外值:
cnt = df.abs() > 3 * df.std()
# axis = 1 計算每一行,只要一行中有一個 True,回傳 True
# True 就表示的是例外值
cnt_ = cnt.any(axis = 1)
df[cnt_]

3.資料轉換
3.1 軸和元素替換
3.1.1 軸的替換
🚩替換軸使用的是函式 rename():
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 10, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns = ['Python', 'Tensorflow', 'Keras'])
display(df)
# 重命名軸索引
df.rename(index = {'A':'AA', 'B':'BB'}, columns = {'Python':'AI'})
display(df)

3.1.2 元素的替換
🚩元素的替換使用 replace() 函式:
# 將5替換為1024
display(df.replace(5, 1024))
# 把0,7替換為2048
display(df.replace([0, 7], 2048))
# 把0替換為519,6替換為666
display(df.replace({0:519, 6:666}))
# 把 Python 這一列值為2的,替換為 -1024
display(df.replace({'Python':2}, -1024))

3.2 map Series元素改變
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 10, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns = ['Python', 'Tensorflow', 'Keras'])
display(df)
# map 用來批量的修改元素
display(df['Keras'].map({6:'辰chen', 9:'AIoT'}))

從運行結果我們可以看出,使用 map 對資料進行替換后,未規定替換的資料會變成空資料,
如果我們想要保留原資料,可以寫自定義函式:
def convert(x):
if x == 6:
return '辰chen'
elif x == 9:
return 'AIoT'
else:
return x
df['Keras'].map(convert)

當然,我們在 Python 中還學習過 lambda 運算式,在這里同樣可以使用:
# 把 Python 這一列大于等于15的值變成True,否則變成False
df['Python'].map(lambda x : True if x >= 5 else False)

3.3 apply元素改變,既支持 Series也支持 DataFrame
3.3.1 apply簡單介紹
創造資料:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0, 101, size = (30, 3)),
columns = ['Python', 'Math', 'English'])
display(df)

apply 對資料進行修改:
def convert(x):
if x < 60:
return '不及格'
elif x < 80:
return '中等'
else:
return '優秀'
df['Python'].apply(convert)

我們現在來把這兩個表格進行合并:
res = df['Python'].apply(convert)
index = list(df.columns).index('Python') + 1
df.insert(loc = index, column = 'Python' + '等級', value = res)
df

如果我們要生成所有學科的等級,我們可以利用 for 回圈:
def convert(x):
if x < 60:
return '不及格'
elif x < 80:
return '中等'
else:
return '優秀'
for col in list(df.columns):
res = df[col].apply(convert)
index = list(df.columns).index(col) + 1
df.insert(loc = index, column = col + '等級', value = res)
df

3.3.2 apply應用
apply 可以對一列資料進行修改:
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 10, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns = ['Python', 'Tensorflow', 'Keras'])
display(df)
# apply 應用,方法:自定義、簡單隱式函式(lambda)
df['Python'] = df['Python'].apply(lambda x : x + 100)
display(df)

map 可以對一列資料進行修改:
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 10, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns = ['Python', 'Tensorflow', 'Keras'])
display(df)
df['Python'] = df['Python'].map(lambda x : x - 100)
display(df)

3.3.3 applymap應用
applymap 可以對整個 DataFrame 進行全部的處理
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 10, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns = ['Python', 'Tensorflow', 'Keras'])
display(df)
def convert(x):
if x < 5:
return 100
else:
return -100
df.applymap(convert)

3.4 transform變形金剛
創建資料:
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 10, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns=['Python', 'Tensorflow', 'Keras'])
df.iloc[4,2] = None # 空資料
display(df)

transform 一樣是支持 lambda 和自定義函式的:
df['Python'].transform(lambda x : x + 10)

def convert(x):
if x < 5:
return 100
else:
return -100
df['Python'].transform(convert)

對一列進行不同的操作:
# 分別對 Python 這一列執行開平方和冪運算
df['Python'].transform([np.sqrt, np.exp])

對多列進行不同的操作:
df.transform({'Python':np.exp, 'Tensorflow':lambda x:x + 10, 'Keras':np.sqrt})

3.5 重排隨機抽樣啞變數
創建資料:
import numpy as np
import pandas as pd
df = pd.DataFrame(data = np.random.randint(0, 10, size = (10, 3)),
index = list('ABCDEFHIJK'),
columns=['Python', 'Tensorflow', 'Keras'])
display(df)

3.5.1 重拍資料
index = np.random.permutation(10)
# 重排資料:
df.take(index)

3.5.2 隨機抽樣
注:隨機抽樣是允許重復的
# 隨機抽樣
index = np.random.randint(0, 10, size = 5)
df.take(index)

3.5.3 啞變數
# 啞變數,獨熱編碼,1表示有,0表示沒有
df = pd.DataFrame({'key':['b','b','a','c','a','b']})
display(df)
display(pd.get_dummies(df,prefix='',prefix_sep=''))
# 可以理解成把字串變成了數字

4.訓練場
4.1 知識點概述
4.1.1 字串替換
將字串:“我在大學的體能極限是1000米3分34秒!” 中的“我”替換為“辰chen”,再將成績轉換為純數字:
import numpy as np
import pandas as pd
s1 = '我在大學的體能極限是1000米3分34秒!'
# 把 '我' 替換為 '辰chen'
s1 = s1.replace('我', '辰chen')
display(s1)
# 將成績轉換為純英文的
s2 = "3'34"
s2 = s2.replace('\'', '.')# \ 表示轉義字符
s2 = float(s2)
display(s2)

4.1.2 報錯演示
score = ["4'03", "4'34", "4'29", "3'48", "3'58", 4]
# for回圈批量替換
for s in score:
s = s.replace('\'', '.')
print(s)

可以看出前幾個資料都進行了正確的替換,只有最后一個資料因無法替換而報錯,報錯的原因在于最后一個資料是 int 型別的資料,是不能呼叫 replace 方法的,replace 只作用于字串
所以我們在替換的程序中可以進行特判:
4.1.3 報錯修復
使用 isinstance() 方法判斷是否是字串型別
score = ["4'03", "4'34", "4'29", "3'48", "3'58", 4]
# for回圈批量替換
for s in score:
# 判斷s是不是字串型別資料,這是一個新知識點
if isinstance(s, str):
s = s.replace('\'', '.')
s = float(s)
print(s, type(s))

4.2 體測成績的部分轉換
4.2.1 男生1000米跑成績轉換
首先我們需要下載一個 Excel 檔案:
鏈接: https://pan.baidu.com/s/1msM5CSZxyJ3TZ5e3TG4XiQ?pwd=w3ut
提取碼: w3ut
復制這段內容后打開百度網盤手機App,操作更方便哦
下載完成之后,把該檔案和我們的代碼放到同一個檔案夾下,這一操作我們在之前的博客中已經反復說到,這里就不再進行演示
我們點開我們下載好的檔案:

表格有男生表,也有女生表,在男生表中通過觀察可以看出,只有 男1000米跑這一列資料是 xx'xx 的形式,我們要把它轉為和 男50米跑,男跳遠這樣的資料形式,并且需要注意到,可能有些同學沒有參加 1000米跑的測驗,我們需要把這些空資料統一賦值為0
import pandas as pd
# 加載男生的體測成績
# 方法一:
df_boy = pd.read_excel('./體測成績.xlsx', sheet_name = 0)
# 方法二:
df_boy = pd.read_excel('./體測成績.xlsx', sheet_name = '男生')
# 空資料處理:沒有參加體能測驗,成績為0
df_boy = df_boy.fillna(0)
def convert(s):
if isinstance(s, str):
s = float(s.replace('\'', '.'))
return s
df_boy['男1000米跑'].map(convert)

4.2.2 男生1000米跑成績轉換并賦值
import pandas as pd
# 加載男生的體測成績
df_boy = pd.read_excel('./體測成績.xlsx', sheet_name = 0)
# 空資料處理:沒有參加體能測驗,成績為0
df_boy = df_boy.fillna(0)
def convert(s):
if isinstance(s, str):
s = float(s.replace('\'', '.'))
return s
df_boy['男1000米跑'] = df_boy['男1000米跑'].map(convert)
# 保存資料,index = False表示不存盤行索引
df_boy.to_excel('./男生體測成績.xlsx', index = False)
# 查看前10個資料
df_boy.head(10)

對于女生資料,我們可以做同樣的處理
import pandas as pd
# 加載女生的體測成績
df_girl = pd.read_excel('./體測成績.xlsx',sheet_name = 1)
# 空資料處理:沒有參加體能測驗,成績為0
df_girl = df_girl.fillna(0)
def convert(s):
if isinstance(s, str):
s = float(s.replace('\'', '.'))
return s
df_girl['女800米跑'] = df_girl['女800米跑'].apply(convert)
# 保存資料,index = False表示不存盤行索引
df_girl.to_excel('./女生體測成績.xlsx', index = False)
# 查看后10個資料
df_girl.tail(10)

4.3 體測成績評分表資料轉換
首先我們下載一個 Exel 檔案:
鏈接: https://pan.baidu.com/s/1wxeENf0tjx5bWxTGxkZGeg?pwd=szmk
提取碼: szmk
復制這段內容后打開百度網盤手機App,操作更方便哦
下載完成之后,把該檔案和我們的代碼放到同一個檔案夾下,這一操作我們在之前的博客中已經反復說到,這里就不再進行演示
我們先按照傳統的方法把資料進行加載查看
import numpy as np
import pandas as pd
score = pd.read_excel('./體側成績評分表.xls')
score

是不是感覺看起來特別的別扭?這是因為我們在我們的 Excel 檔案中,我們最上方一行每個都占了兩列的原因,所以代碼運行中的 Unnamed1,Unnamed3 其實就是填充,

針對上述現象,我們可以按如下方法執行:
import numpy as np
import pandas as pd
# header:告訴 pandas 第一行和第二行作為列索引
score = pd.read_excel('./體側成績評分表.xls',header = [0, 1])
score

我們來觀察資料:

發現成績的形式都是:xx'xx" 的形式,現在我們想把它轉為數字的形式:
def convert(x):
if isinstance(x, str):
s = float(x.replace('\"', '').replace('\'', '.'))
# 洗掉 " 替換 ' 為 .
return s
x = '''3'30"'''
convert(x)

我們用上述方法對男生考核標準進行轉換:
def convert(x):
if isinstance(x, str):
s = float(x.replace('\"', '').replace('\'', '.'))
return s
# 男生考核標準轉換
score.iloc[:, -4] = score.iloc[:, -4].apply(convert)
score

同樣的方法,對女生資訊進行轉換:
score = pd.read_excel('./體側成績評分表.xls',header=[0, 1])
def convert(x):
if isinstance(x, str):
s = float(x.replace('\"', '').replace('\'', '.'))
return s
# 男生考核標準轉換
score.iloc[:, -4] = score.iloc[:, -4].apply(convert)
# 女生考核標準轉換
score.iloc[:, -2] = score.iloc[: , -2].apply(convert)
score

最后保存我們的檔案:
score = pd.read_excel('./體側成績評分表.xls',header=[0, 1])
def convert(x):
if isinstance(x, str):
s = float(x.replace('\"', '').replace('\'', '.'))
return s
# 男生考核標準轉換
score.iloc[:, -4] = score.iloc[:, -4].apply(convert)
# 女生考核標準轉換
score.iloc[:, -2] = score.iloc[: , -2].apply(convert)
score.to_excel('./體側成績評分表_處理.xlsx', header=[0, 1])

再來查看以下我們的資料:
pd.read_excel('./體側成績評分表_處理.xlsx', header = [0, 1])

可以看到第一列多了一些奇奇怪怪的東西,我們用 index_col = 0 洗掉:
# index_col = 0 使用第一列作為行索引
pd.read_excel('./體側成績評分表_處理.xlsx', header = [0, 1], index_col = 0)

4.4 男生體測分數成績轉換
4.4.1 男生1000米跑成績分數轉換
注:代碼處于運行中將顯示:

下列代碼運行十幾秒,幾十秒甚至幾分鐘都是正常的,耐心等待運行結果即可,
%%time
import pandas as pd
# 加載處理之后的男生體測成績
df_boy = pd.read_excel('./男生體測成績.xlsx')
# 加載成績評分表
score = pd.read_excel('./體側成績評分表_處理.xlsx', header = [0,1],index_col = 0)
# 定義轉換方法
def convert(x):
if x == 0: # 說明沒有參加體能測驗,分數為0分
return 0
for i in range(20): # 成績劃分20等級
if x <= score['男1000米跑']['成績'][i]:
return score['男1000米跑']['分數'][i]
return 0 # 說明跑的太慢了,分數為0分
df_boy['男1000米跑'].apply(convert)

4.4.2 男生1000米跑成績分數轉換并賦值
%%time
import pandas as pd
# 加載處理之后的男生體測成績
df_boy = pd.read_excel('./男生體測成績.xlsx')
# 加載成績評分表
score = pd.read_excel('./體側成績評分表_處理.xlsx', header = [0, 1])
# 定義轉換方法
def convert(x):
if x == 0: # 說明沒有參加體能測驗,分數為0分
return 0
for i in range(20): # 成績劃分20等級
if x <= score['男1000米跑']['成績'][i]:
return score['男1000米跑']['分數'][i]
return 0 # 說明跑的太慢了,分數為0分
df_boy['男1000米跑' + '分數'] = df_boy['男1000米跑'].apply(convert)
df_boy.head(10)

4.4.3 批量轉換男生速度類成績分數
%%time
import numpy as np
import pandas as pd
df_boy = pd.read_excel('./男生體測成績.xlsx')
score = pd.read_excel('./體側成績評分表_處理.xlsx', header = [0,1], index_col = 0)
cols = ['男1000米跑', '男50米跑']
def convert(x, col):
if x == 0: # 說明沒有參加體能測驗,分數為0分
return 0
for i in range(20): # 成績劃分20等級
if x <= score[col]['成績'][i]:
return score[col]['分數'][i]
return 0 # 說明跑的太慢了,分數為0分
for col in cols:
# args 傳入的引數 (col,)元組
s = df_boy[col].apply(convert, args = (col,))
columns = df_boy.columns.to_list()
index = columns.index(col) + 1 # 這一列后面
# 向這一列后面添加一列:分數
df_boy.insert(loc = index, column = col + '分數', value = s)
df_boy.head()

4.4.4 批量轉換男生力量型成績分數并保存
%%time
# convert自定義,名字任意
def convert(x, col):
for i in range(20): # 成績劃分20等級
if x >= score[col]['成績'][i]:
return score[col]['分數'][i]
return 0 # 說明跳遠不達標,分數為0分
cols = ['男跳遠', '男體前屈', '男引體', '男肺活量']
for col in cols:
# apply ,args = (col,)代表某一列,成績分數轉換
s = df_boy[col].apply(convert, args = (col,))
columns = df_boy.columns.to_list()
# 后面插入一列
index = columns.index(col) + 1
df_boy.insert(loc = index, column = col + '分數', value = s)
display(df_boy.head())
df_boy.to_excel('./男生體測成績-分數.xlsx', index = False)

4.5 女生體測成績分數轉換
%%time
import numpy as np
import pandas as pd
df_girl = pd.read_excel('./女生體測成績.xlsx')
score = pd.read_excel('./體側成績評分表_處理.xlsx', header = [0,1],index_col = 0)
# 速度型別成績分數批量轉換
cols = ['女800米跑', '女50米跑']
def convert(x, col):
if x == 0: # 說明沒有參加體能測驗,分數為0分
return 0
for i in range(20): # 成績劃分20等級
if x <= score[col]['成績'][i]:
return score[col]['分數'][i]
return 0 # 說明跑的太慢了,分數為0分
for col in cols:
s = df_girl[col].apply(convert, args = (col,))
columns = df_girl.columns.to_list()
index = columns.index(col) + 1
df_girl.insert(loc = index, column = col + '分數', value = s)
# 力量型成績分數批量轉換
cols = ['女跳遠', '女體前屈', '女仰臥', '女肺活量']
def convert(x, col):
for i in range(20): # 成績劃分20等級
if x >= score[col]['成績'][i]:
return score[col]['分數'][i]
return 0 # 說明跳遠不達標,分數為0分
for col in cols:
s = df_girl[col].apply(convert, args = (col,))
columns = df_girl.columns.to_list()
index = columns.index(col) + 1
df_girl.insert(loc = index, column = col + '分數', value = s)
df_girl.to_excel('./女生體測成績-分數.xlsx', index = False)
df_girl.head(10)

4.6 保存成績
最后我們把男女生成績整合到一個檔案當中:
with pd.ExcelWriter('./分數匯總.xlsx') as writer:
df_boy.to_excel(writer, sheet_name = '男生', index = False)
df_girl.to_excel(writer, sheet_name = '女生', index = False)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417153.html
標籤:AI
