大Pandas的多列因子分解

2024-09-28 17:30:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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]

也就是说,我想确定一个数据帧的几列中的每一个唯一的值元组,为每一列分配一个顺序索引,并计算数据帧中每一行属于哪个索引。

Factorize仅适用于单个列。熊猫有多栏等效函数吗?


Tags: 数据函数importdataframepandasdf顺序as
3条回答

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

In [23]: df.drop_duplicates()
Out[23]: 
      x  y
   0  1  1
   1  1  2
   2  2  2

编辑

为了实现您的目标,您可以将原来的df加入drop_duplicated:

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])))

打印ind将给出

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

首先需要创建一个元组数组,pandas.lib.fast_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]

相关问题 更多 >