<
>

数据清洗之 高阶函数处理

2020-07-28 19:54:03 来源:易采站长站 作者:

高阶函数处理

在dataframe中使用apply方法,调用自定义函数对数据进行处理
函数apply,注意axis
可以使用astype函数对数据进行转换
可以使用map函数进行数据转换

import pandas as pd
import numpy as np
import os

os.getcwd()

'D:JupyternotebookPython数据清洗实战数据清洗之数据转换'

os.chdir('D:JupyternotebookPython数据清洗实战数据')

df = pd.read_csv('sam_tianchi_mum_baby.csv', dtype=str, encoding='utf-8')

df.head(5)

user_idbirthdaygender
02757201303111
1415971201211110
21372572201201301
310339332201109100
410642245201302130

def f(x):
if '0' in str(x):
return '女'
elif '1' in str(x):
return '男'
else:
return '未知'

# apply函数可做很多其他处理
df['性别'] = df['gender'].apply(f)

df.head(5)

user_idbirthdaygender性别
02757201303111
1415971201211110
21372572201201301
310339332201109100
410642245201302130

# 查看性别为未知数据
df[df['gender'] == '2'].head(5)

user_idbirthdaygender性别
4649167150201308182未知
4749983255201402062未知
5152529655201306112未知
5857711375201304202未知
10699665637201309262未知

del df['性别']

# map函数主要用于映射
df['性别'] = df['gender'].map({'0': '女性', '1':'男性', '2': '未知'})

df.head(5)

user_idbirthdaygender性别
02757201303111男性
1415971201211110女性
21372572201201301男性
310339332201109100女性
410642245201302130女性

del df['性别']

# map函数也可传入自己定义的函数
df['性别'] = df['gender'].map(f)

df.head(5)

user_idbirthdaygender性别
02757201303111
1415971201211110
21372572201201301
310339332201109100
410642245201302130

# 脱敏处理
# 可使用lambda函数
df['user_id'].apply(lambda x: str(x).replace(x[1:3], '**')).head(5)

0        2**7
1 4**971
2 1**2572
3 1**39332
4 1**42245
Name: user_id, dtype: object

df['birthday'].apply(lambda x: x[0:4]).head(5)

0    2013
1 2012
2 2012
3 2011
4 2013
Name: birthday, dtype: object


作者:若尘

暂时禁止评论

微信扫一扫

易采站长站微信账号