【问题标题】:multi-column factorize in pandas熊猫中的多列分解
【发布时间】:2013-05-03 10:31:19
【问题描述】:

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

【问题讨论】:

  • 你的预期输出是什么?
  • 评论中的列表 -- 每个不同 (x, y) 值的唯一顺序索引

标签: python pandas enumeration data-cleaning


【解决方案1】:

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

【讨论】:

  • 谢谢——它以相当紧凑的形式给出了我正在寻找的答案
  • 我收到以下错误:{AttributeError}module 'pandas' has no attribute 'lib'
  • 函数可以在pd._libs.lib.fast_zip下找到。不知道什么时候改变的。
【解决方案2】:

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

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]

【讨论】:

    【解决方案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
    

    【讨论】:

    • 我不想删除它们,而是为每对不同的值分配一个唯一索引(即我最终想向数据框添加一个新列,其值为 [0, 1 , 2, 2, 1, 0])。
    【解决方案4】:
    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]
    

    【讨论】:

    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 2023-02-26
    • 2021-05-08
    • 2018-04-18
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多