DataFrame的apply()、applymap()、map()方法
是对dataframe进行处理。
总结:
apply():对dataframe的所有 列或者行,进行操作
applymap():对dataframe的 所有数据进行操作
map():对dataframe的 某一列数据进行操作
① map()
df.map函数是针对于dataframe中的 某一列数据进行操作:
测试dataframe:
test
data={'Survived': [0, 1, 1, 1, 0], 'Pclass': [3, 1, 3, 1, 3], 'Sex': [0, 1, 1, 1, 0], 'Age': [22.0, 38.0, 26.0, 35.0, 35.0], 'SibSp': [1, 1, 0, 1, 0], 'Parch': [0, 0, 0, 0, 0], 'Fare': [7.25, 71.2833, 7.925, 53.1, 8.05], 'Embarked': ['S', 'C', 'S', 'S', 'S'], 'Title': [1, 3, 2, 3, 1]}
tes=pd.DataFrame(data)
test表格如下:
Survived Pclass Sex Age SibSp Parch Fare Embarked Title
0 0 3 0 22.0 1 0 7.2500 S 1
1 1 1 1 38.0 1 0 71.2833 C 3
2 1 3 1 26.0 0 0 7.9250 S 2
3 1 1 1 35.0 1 0 53.1000 S 3
4 0 3 0 35.0 0 0 8.0500 S 1
对sex列进行处理:实现字典的映射。
>>test['Sex'].map({0:'female',1:'male'})
0 female
1 male
2 male
3 male
4 female
Name: Sex, dtype: object
对Fare的每个值进行加1处理
>>test['Fare'].map(lambda x: x+1)
0 8.2500
1 72.2833
2 8.9250
3 54.1000
4 9.0500
Name: Fare, dtype: float64
② apply()
DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)
各参数的含义:
func:就是你传入的函数
axis:{0 or ‘index’, 1 or ‘columns’}, 默认为 0,也就是列
0:将函数应用于每列
1:将函数应用于每行
与我们索引时的不同,索引时index代表每行。
raw:
对每一列数据,取最大值,那么axis为0,或者’index’
>>test
Survived Pclass Sex Age SibSp Parch Fare Embarked Title
0 0 3 0 22.0 1 0 7.2500 S 1
1 1 1 1 38.0 1 0 71.2833 C 3
2 1 3 1 26.0 0 0 7.9250 S 2
3 1 1 1 35.0 1 0 53.1000 S 3
4 0 3 0 35.0 0 0 8.0500 S 1
>>test.apply(lambda x:max(x),axis=0)
Survived 1
Pclass 3
Sex 1
Age 38.0
SibSp 1
Parch 0
Fare 71.2833
Embarked S
Title 3
dtype: object
>>test.apply(lambda x:max(x),axis="index")
Survived 1
Pclass 3
Sex 1
Age 38.0
SibSp 1
Parch 0
Fare 71.2833
Embarked S
Title 3
dtype: object
③ applymap()
用applymap()函数,对dataframe中的每一个数进行操作。
>>test.drop('Embarked',axis=1,inplace=True)
test
Survived Pclass Sex Age SibSp Parch Fare Title
0 0 3 0 22.0 1 0 7.2500 1
1 1 1 1 38.0 1 0 71.2833 3
2 1 3 1 26.0 0 0 7.9250 2
3 1 1 1 35.0 1 0 53.1000 3
4 0 3 0 35.0 0 0 8.0500 1
>>test.applymap(lambda x:x+1)
Survived Pclass Sex Age SibSp Parch Fare Title
0 1 4 1 23.0 2 1 8.2500 2
1 2 2 2 39.0 2 1 72.2833 4
2 2 4 2 27.0 1 1 8.9250 3
3 2 2 2 36.0 2 1 54.1000 4
4 1 4 1 36.0 1 1 9.0500 2
Original: https://blog.csdn.net/m0_52985451/article/details/120940952
Author: 云梦之上
Title: DataFrame的apply()、applymap()、map()方法
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/674908/
转载文章受原作者版权保护。转载请注明原作者出处!