繁体   English   中英

熊猫中的多列分解

[英]multi-column factorize in pandas

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 中是否有多列等效函数?

您需要先创建一个元组的 ndarray, 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]

我不确定这是否是一个有效的解决方案。 可能有更好的解决方案。

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]

您可以使用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
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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM