【问题标题】:getting the unique values rowise?获取唯一值行明智?
【发布时间】:2018-11-07 05:18:16
【问题描述】:

我有一个column,不同的活动由,分隔

Activities

Bathing the puppy, cooking for family
cooking for family, cooking for family
morning walk, cooking for family, Bathing the puppy
Bathing the puppy, Bathing the puppy,Bathing the puppy

如何创建一个单独的column,其中包含每行不同活动的计数。

我希望输出如下:

Activities                                                  Unique Activities

Bathing the puppy, cooking for family                         2
cooking for family, cooking for family                        1
morning walk, cooking for family, Bathing the puppy           3
Bathing the puppy, Bathing the puppy,Bathing the puppy        1

我在pandas 中尝试了nunique 方法,但这适用于整个列,而不是在每一行中给我不同的值。

【问题讨论】:

    标签: python-2.7 pandas row


    【解决方案1】:

    在一个实际示例中,您可能需要处理大小写和标点符号问题。在nunique 中指定axis=1,以便它跨行运行。

    df['Unique Activities'] = df.Activities.str.split(r',\s?', expand=True).nunique(1)
    

    输出:

                                                   Activities  Unique Activities
    0                   Bathing the puppy, cooking for family                  2
    1                  cooking for family, cooking for family                  1
    2     morning walk, cooking for family, Bathing the puppy                  3
    3  Bathing the puppy, Bathing the puppy,Bathing the puppy                  1
    

    【讨论】:

    • 该解决方案有效。非常感谢您的快速回复并节省了我的时间:)
    • 只是一个查询,(r',\s?', expand=True) 到底在做什么? @ALollz
    • @suryarahul 它基于逗号和可选空格分割字符串,这是最后一行所需的。所以分隔符是','', '。展开变成DataFrame,因此我们可以在拆分字符串中使用nunique()。如果您查看df.Activities.str.split(r',\s?', expand=True),您可以看到它将您的字符串拆分成什么。
    • 非常感谢您纠正我的疑问 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    相关资源
    最近更新 更多