【问题标题】:How to count the unique values of each row in one column with python?如何用python计算一列中每一行的唯一值?
【发布时间】:2017-12-20 07:00:58
【问题描述】:

我有这样一个数据框:

id countries
01 [UK,UK,UK,US]
02 [US,US,US,US]
03 [FR,UK,CN,US]

我想计算每个 id 存在多少个国家。喜欢的结果应该是这样的:

id countries counts
01 [UK,UK,UK,US] 2
02 [US,US,US,US] 1
03 [FR,UK,CN,US] 4

【问题讨论】:

  • 为什么要在不使用的时候导入包?
  • @GarbageCollector 嗯......我的错,它被用于其他人。我会删除它。谢谢。

标签: python count unique


【解决方案1】:

如果值为lists 将它们转换为set 并得到length

print (type(df.loc[0, 'countries']))
<class 'list'>

df['counts'] = df['countries'].apply(lambda x: len(set(x)))
print (df)
   id         countries  counts
0   1  [UK, UK, UK, US]       2
1   2  [US, US, US, US]       1
2   3  [FR, UK, CN, US]       4

或者如果值为strings,首先删除[]并拆分:

print (type(df.loc[0, 'countries']))
<class 'str'>

df['counts'] = df['countries'].str.strip('[]').str.split(',').apply(lambda x: len(set(x)))
print (df)
   id      countries  counts
0   1  [UK,UK,UK,US]       2
1   2  [US,US,US,US]       1
2   3  [FR,UK,CN,US]       4

【讨论】:

    猜你喜欢
    • 2014-04-07
    • 2023-04-06
    • 2021-11-12
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多