python – Pandas组中的唯一值

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

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

最佳答案 你不需要定义那个函数,你可以用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

希望能帮助到你!

点赞