问题描述
pandas factorize
函数将系列中的每个唯一值分配给基于0的顺序索引,并计算每个系列条目所属的索引.
The pandas factorize
function assigns each unique value in a series to a sequential, 0-based index, and calculates which index each series entry belongs to.
我想在多列上完成pandas.factorize
的等效功能:
I'd like to accomplish the equivalent of pandas.factorize
on multiple columns:
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]
也就是说,我要确定数据帧的几列中的每个值的唯一元组,为每个值分配一个顺序索引,并计算数据帧中的每一行属于哪个索引.
That is, I want to determine each unique tuple of values in several columns of a data frame, assign a sequential index to each, and compute which index each row in the data frame belongs to.
Factorize
仅适用于单列.熊猫中有多列等效功能吗?
Factorize
only works on single columns. Is there a multi-column equivalent function in pandas?
推荐答案
您需要先创建一个元组的ndarray,pandas.lib.fast_zip
可以在cython循环中非常快速地完成此操作.
You need to create a ndarray of tuple first, pandas.lib.fast_zip
can do this very fast in cython loop.
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]
这篇关于 pandas 中的多列分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!