Pandas组内的唯一值

时间:2017-01-26 18:26:04

标签: python pandas dataframe data-science

我有一个我需要分组的数据帧,然后是子组。从子组我需要返回子组的内容以及列的唯一值。

df = pandas.DataFrame({'country': pandas.Series(['US', 'Canada', 'US', 'US']),
                       'gender': pandas.Series(['male', 'female', 'male', 'female']),
                       'industry': pandas.Series(['real estate', 'shipping', 'telecom', 'real estate']),
                       'income': pandas.Series([1, 2, 3, 4])})

def subgroup(g):
    return g.groupby(['gender'])

s = df.groupby(['country']).apply(subgroup)

从s开始,我如何计算“行业”的独特性以及它所分组的“性别”?

--------------------------------------------
| US     | male   | [real estate, telecom] |
|        |----------------------------------
|        | female | [real estate]          |
--------------------------------------------
| Canada | female | [shipping]             |
--------------------------------------------

1 个答案:

答案 0 :(得分:2)

您不需要定义该功能,您可以单独使用groupby()和unique()来解决您的问题;

尝试:

df.groupby(['country','gender'])['industry'].unique()

输出:

country  gender
Canada   female                [shipping]
US       female             [real estate]
         male      [real estate, telecom]
Name: industry, dtype: object
希望它有所帮助!