1. Numpy中的where函数
首先看下官网文档给出的定义:
numpy.where(condition[, x, y])
Return elements, either from x or y, depending on condition
依赖于所给定条件,决定返回x还是返回y,如果条件为真,返回x,否则返回y。
- 对于一维数据
对于一维数据而言上述定义等价于:
[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
具体例子如下:
con = [True,True,False,True,True,True,False ]
data1 = np.arange(7)
data2 = np.arange(14,21)
print (np.where(con,data1,data2))
结果为:
[ 0 1 16 3 4 5 20]
- 对于二维数据
x = np.random.randn(4,4)
print (x)
print(np.where(x>0,2,-2)) #将数据集中所有大于0的全部置为2,小于0的全部置为-2
最近在做类别型变量的特征交叉问题时,发现同样可以使用where函数来达到目的,比如有两个类别型变量分别是cat1和cat2,cat1有ABC三种可能取值,cat2有DEF三种可能取值,两个类别型特征做交叉以后生成的新变量就是笛卡尔乘积,共有9种可能取值,具体实现代码如下:
data = pd.read_excel(r'C:\Users\Lenovo\Desktop\test.xlsx')
# cat1:ABC ;cat2:DFT
print (data)
data['cross_cat1_cat2'] = np.where((data['cat1']=='A') & (data['cat2']=='D'),'AD',
np.where((data['cat1'] == 'A') & (data['cat2'] == 'F'), 'AF',
np.where((data['cat1'] == 'A') & (data['cat2']== 'T'), 'AT',
np.where((data['cat1'] == 'B') & (data['cat2'] == 'T'), 'BT',
np.where((data['cat1'] == 'B') & (data['cat2'] == 'F'), 'BF',
np.where((data['cat1'] == 'B') & (data['cat2'] == 'D'), 'BD',
np.where((data['cat1'] == 'C') & (data['cat2'] == 'T'), 'CT',
np.where((data['cat1'] == 'C') & (data['cat2'] == 'F'), 'CF',
np.where((data['cat1'] == 'C') & (data['cat2'] == 'D'), 'CD',"OTHERS" )))))))))
print (data)
最后生成效果如下所示:
Paste_Image.png
持续更新中。。。。。。