Python 熊猫中的多列因子分解

Python 熊猫中的多列因子分解,python,pandas,enumeration,data-cleaning,Python,Pandas,Enumeration,Data Cleaning,pandasfactorize函数将序列中的每个唯一值分配给一个顺序的、基于0的索引,并计算每个序列条目所属的索引 我想在多个列上完成与熊猫分解相当的pandas.factorize: import pandas as pd df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2, 2, 2, 2, 1]}) pd.factorize(df)[0] # would like [0, 1, 2, 2, 1, 0] 也就是说,我想确定一个数据帧的

pandas
factorize
函数将序列中的每个唯一值分配给一个顺序的、基于0的索引,并计算每个序列条目所属的索引

我想在多个列上完成与熊猫分解相当的
pandas.factorize

import pandas as pd
df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2, 2, 2, 2, 1]})
pd.factorize(df)[0] # would like [0, 1, 2, 2, 1, 0]
也就是说,我想确定一个数据帧的几列中每个唯一的值元组,为每个元组分配一个顺序索引,并计算数据帧中每一行所属的索引


Factorize
仅适用于单列。pandas中是否有多列等效函数?

您可以使用
删除重复项
删除那些重复的行

In [23]: df.drop_duplicates()
Out[23]: 
      x  y
   0  1  1
   1  1  2
   2  2  2
编辑 为了实现您的目标,您可以将原始df加入到drop_duplicated df中:

In [46]: df.join(df.drop_duplicates().reset_index().set_index(['x', 'y']), on=['x', 'y'])
Out[46]: 
   x  y  index
0  1  1      0
1  1  2      1
2  2  2      2
3  2  2      2
4  1  2      1
5  1  1      0

我不确定这是否是一个有效的解决方案。也许有更好的解决办法

arr=[] #this will hold the unique items of the dataframe
for i in df.index:
   if list(df.iloc[i]) not in arr:
      arr.append(list(df.iloc[i]))
所以打印arr会给你

>>>print arr
[[1,1],[1,2],[2,2]]
为了保存索引,我将声明一个ind数组

ind=[]
for i in df.index:
   ind.append(arr.index(list(df.iloc[i])))
我会给你的

 >>>print ind
 [0,1,2,2,1,0]

首先需要创建一个元组数组,
pandas.lib.fast\u-zip可以在cython循环中非常快速地完成这项工作

import pandas as pd
df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2, 2, 2, 2, 1]})
print pd.factorize(pd.lib.fast_zip([df.x, df.y]))[0]
输出为:

[0 1 2 2 1 0]

您期望的输出是什么?注释中的列表--每个不同(x,y)值的唯一顺序索引我不想删除它们,而是为每对不同的值分配一个唯一的索引(即,我最终想在数据框中添加一个新列,值为[0,1,2,2,1,0])。谢谢--这给出了我想要的答案,在一个相当紧凑的表单中,我得到以下错误:{AttributeError}模块“pandas”没有属性“lib”。该函数可以在
pd.\u libs.lib.fast\u zip
下找到。不确定它何时更改。请解释您的代码与OP的不同之处,以及如何解决问题。我推荐这本关于创建有用答案的指南
df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2, 2, 2, 2, 1]})
tuples = df[['x', 'y']].apply(tuple, axis=1)
df['newID'] = pd.factorize( tuples )[0]