Pandas中map apply applymap可以对DataFrame进行逐行、逐列和逐元素的操作。
依赖的数据集样例:
import pandas as pd
ex_data = pd.DataFrame({
'class': ['A', 'A', 'B', 'C', 'B', 'B', 'C', 'A', 'B'],
'gender': ['男', '女', '女', '男', '女', '男', '男', '男', '男'],
'score_math': [95, 96, 85, 93, 84, 88, 59, 88, 89],
'score_music': [79, 90, 85, 92, 90, 70, 89, 86, 74]})
Series数据处理
1 map
将样例中gender列的男替换为1,女替换为0。
1.1 使用字典进行映射
ex_data['gender'] = ex_data['gender'].map({"男": 1, "女": 0})
如将gender列映射为英文表示:
gender_df = pd.DataFrame({
'gender': ['男', '女'],
'eng_gender': ['male', 'female']})
gender_dict = gender_df.set_index('gender')['eng_gender'].to_dict()
ex_data['gender'] = ex_data['gender'].map(gender_dict, na_action='ignore')
1.2 使用函数进行映射
def gender_map(x):
gender = 1 if x == "男" else 0
return gender
ex_data['gender'] = ex_data['gender'].map(gender_map)
不管用字典还是函数进行映射,map方法都是把对应的数据逐个当做参数传入字典或函数中,得到映射后的值。
2 apply
与map很类似,但是允许传入功能更为复杂的函数。传入map的函数只能接收一个参数,而apply支持多个参数。比如将数学课的乘积统一减去3分:
def score_math_sub(x, bias):
return x + bias
# 以元组的方式传入额外的参数
ex_data['score_math'] = ex_data['score_math'].apply(score_math_sub, args=(-3,))
DataFrame数据处理
1 apply
比如对得分列进行取对数和求和的操作:
print(ex_data[['score_math', 'score_music']].apply(np.sum, axis=0))
print(ex_data[['score_math', 'score_music']].apply(np.log, axis=0))
比如要求数学和音乐两门课的平均分:
def Avg_calculate(series):
math_score = series["score_math"]
math_music = series["score_music"]
Avg_score= (math_score + math_music) / 2
return Avg_score
ex_data['Avg_score'] = ex_data.apply(Avg_calculate, axis=1)
2 applymap
用法相对简单,会对DataFrame中的每个单元格执行指定函数的操作。
比如df中全部改为小写:
ex_numdata = ex_data[['class']]
ex_numdata = ex_numdata.applymap(lambda x: x.lower())