pandas的factorize(),numpy库unique函数

本文介绍了pandas的factorize()函数,它将Series中的标称数据映射为数字,相同元素映射为相同数字,返回值包括映射数组和元素索引。同时,文章解析了numpy库的unique()函数,该函数返回数组中的唯一值并可选返回其在原始数组中的下标和逆映射下标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、factorize函数可以将Series中的标称型数据映射称为一组数字,相同的标称型映射为相同的数字。

factorize函数的返回值是一个tuple(元组),元组中包含两个元素。

第一个元素是一个array,其中的元素是标称型元素映射为的数字;

第二个元素是Index类型,其中的元素是所有标称型元素,没有重复。

# coding=utf-8
import numpy as np
import xgboost as xgb
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import csv
from pandas import DataFrame

df = pd.DataFrame({"id":[1,2,3,4,5,6,3,2], "raw_grade":['a', 'b', 'b','a', 'a', 'e','c','a']})
print df
print '\n'
x = pd.factorize(df.raw_grade)
print x

结果:

   id raw_grade
0   1         a
1   2         b
2   3         b
3   4         a
4   5         a
5   6         e
6   3         c
7   2         a


(array([0, 1, 1, 0, 0, 2, 3, 0], dtype=int64), Index([u'a', u'b', u'e', u'c'], dtype='object'))

2、numpy库unique函数解析


unique()函数返回参数数组中所有不同的值,并按照从小到大排序

该函数有两个可选参数:

return_index: True 表示unique()后的新数据在原始数组中的下标;

return_inverse :True      表示重建后的数组中各元素对应的下标 在原始数组或列表中表示出来;


1)对于一维列表或数组A: 

import numpy as np
A = [1, 2, 2, 3, 4, 3]
a = np.unique(A)
print a            # 输出为 [1 2 3 4]
a, b, c = np.unique(A, return_index=True, return_inverse=True)
print a, b, c      # 输出为 [1 2 3 4], [0 1 3 4], [0 1 1 2 3 2]


注意:上面与下面的不之同之处

A = [4, 2, 2, 3, 1, 3]
a = np.unique(A)
print a            # 输出为 [1 2 3 4]
a, b, c = np.unique(A, return_index=True, return_inverse=True)
print a, b, c      # 输出为 [1 2 3 4] [4 1 3 0] [3 1 1 2 0 2]
说明:

c  重建后的列表[1 2 3 4]中各元素对应的下标 为:0,1,2,3  ,  在原始数组或列表中表示出来[3 1 1 2 0 2];即4的下标为3,3的下标为2,2的下标为1,1的下标为0.

2)对于二维数组(“darray数字类型”): 

A = [[1, 2], [3, 4], [5, 6], [1, 2]]
A = np.array(A)   #列表类型需转为数组类型
a, b, c = np.unique(A.view(A.dtype.descr * A.shape[1]), return_index=True, return_inverse=True)
print a, b, c     #输出为 [(1, 2) (3, 4) (5, 6)], [0 1 2], [0 1 2 0]





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值