pandas-数值映射和替换

发布时间 2023-09-08 19:27:20作者: 贝壳里的星海

pandas-数值映射和替换

映射列值是指将一个列中的某些特定值映射为另外一些值,常用于数据清洗和转换。

映射map()

Series.map(arg,na_action=None)
arg: 接收 function、dict 或 Series,表示映射关系;
import pandas as pd  
  
data = {  
    'Name': ['Tom', 'Jerry', 'Spike', 'Tyke'],  
    'Age': [3, 4, 6, 1]  
}  
  
df = pd.DataFrame(data)  
# 使用一个函数映射Name列  
df['Name'] = df['Name'].map({'Tom': 'Top Cat', 'Jerry': 'The Terrorist'})  
print(df)

输入字典dict

import pandas as pd  
  
# 创建一个简单的 DataFrame  
df = pd.DataFrame({'name': ['xiaomin', 'xiaoxin', 'wanglei'], 
                   'age': [29, 25, 31], 
                   'gender':['man','woman','man'],
                   'score':[90,92,98],
                   'home': ['beijing', 'chengdu', 'shanhai'],
                   'indx':['A','V','E'],
                   })  

print(df)
#       name  age gender  score     home indx
# 0  xiaomin   29    man     90  beijing    A
# 1  xiaoxin   25  woman     92  chengdu    V
# 2  wanglei   31    man     98  shanhai    E

gender_map={'man':'1','woman':'0'}
df['gender']=df['gender'].map(gender_map)
print(df)
#       name  age gender  score     home indx
# 0  xiaomin   29      1     90  beijing    A
# 1  xiaoxin   25      0     92  chengdu    V
# 2  wanglei   31      1     98  shanhai    E

输入函数

import pandas as pd  
  
# 创建一个简单的 DataFrame  
df = pd.DataFrame({'name': ['xiaomin', 'xiaoxin', 'wanglei'], 
                   'age': [29, 25, 31], 
                   'gender':['man','woman','man'],
                   'score':[90,92,98],
                   'home': ['beijing', 'chengdu', 'shanhai'],
                   'indx':['A','V','E'],
                   })  
print(df)

def gender_map(x):
    gender = 1 if x == "man" else 0
    return gender
#注意这里传入的是函数名,不带括号
data["gender"] = data["gender"].map(gender_map)
#       name  age gender  score     home indx
# 0  xiaomin   29      1     90  beijing    A
# 1  xiaoxin   25      0     92  chengdu    V
# 2  wanglei   31      1     98  shanhai    E

df['score'] = df['score'].map(lambda x : "%.3f"%x)
print(df)
#       name  age gender   score     home indx
# 0  xiaomin   29      1  90.000  beijing    A
# 1  xiaoxin   25      0  92.000  chengdu    V
# 2  wanglei   31      1  98.000  shanhai    E

替换replace()

DataFrame.replace(self, to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')

to_replace: 接收 str、regex、list、dict、Series、int、float 或者 None,表示将被替换的值;
			1)numeric: 等于to_replace的数值将被替换为value
			2)str: 完全匹配to_replace的字符串将被替换为值
			3)regex: 匹配to_replace的正则表达式将被替换为值
value:		接收标量、字典、列表、str、正则表达式,默认为 None;用于替换与 to_replace 匹配的任何值的值;
inplace:	接收布尔值,默认为 False,如果是 True,将修改原来的数据;
limit:		接收 int,默认为 None,用于限制填充次数;
regex:		接收 bool 或与 to_replace 相同的类型,默认为 False,表示是否将 to_replace 或 value 解释为正则表达式
method:		取值为 {'pad','ffill','bfill',无}
# 单数替换
s = pd.Series([0, 1, 2, 3, 4])
s.replace(0, 5)
#0    5
#1    1
#2    2
#3    3
#4    4
#dtype: int64

import pandas as pd  
import numpy as np
# 创建一个简单的 DataFrame  
df = pd.DataFrame(np.arange(1,16).reshape(3,5),
                  columns=list("abcef"))  
print(df)
#     a   b   c   e   f
# 0   1   2   3   4   5
# 1   6   7   8   9  10
# 2  11  12  13  14  15


df.replace([0, 1, 2, 3], 4)


df.replace([0, 1, 2, 3], [4, 3, 2, 1])


s.replace([1, 2], method='bfill')

dtype: int64


>>> df.replace({0: 10, 1: 100})
     A  B  C
0   10  5  a
1  100  6  b
2    2  7  c
3    3  8  d
4    4  9  e
>>> df.replace({'A': 0, 'B': 5}, 100)
     A    B  C
0  100  100  a
1    1    6  b
2    2    7  c
3    3    8  d
4    4    9  e
>>> df.replace({'A': {0: 100, 4: 400}})
     A  B  C
0  100  5  a
1    1  6  b
2    2  7  c
3    3  8  d
4  400  9  e

参考资料

https://zhuanlan.zhihu.com/p/100064394

https://blog.csdn.net/fullbug/article/details/122786172

https://www.cnblogs.com/wang_yb/p/17619979.html