【问题标题】:Find Unique Values in a Pandas Dataframe Cell在 Pandas 数据框单元格中查找唯一值
【发布时间】:2019-01-30 15:38:46
【问题描述】:

样本 DF

data = {'name': ['Jason , Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 
        'year': ['2012 , 2012 , 2016 , 2016', 2012, 2013, 2014, 2014], 
        'reports': ['4 , 4 , 5 , 6 , 6 , 7', 24, 31, 2, 3]}
df1 = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])

看起来像

                     name            ...                                   year
Cochice     Jason , Jason            ...              2012 , 2012 , 2016 , 2016
Pima                Molly            ...                                   2012
Santa Cruz           Tina            ...                                   2013
Maricopa             Jake            ...                                   2014
Yuma                  Amy            ...                                   2014

我希望Cochice 索引的每个单元格都有唯一值。我尝试了drop_duplicatesnunique,但它们都不起作用。

在我原来的 df 中,列数可以超过 3

输出 Df

             name  reports       year
Cochice     Jason  4,5,6,7  2012,2016
Pima        Molly       24       2012
Santa Cruz   Tina       31       2013
Maricopa     Jake        2       2014
Yuma          Amy        3       2014

【问题讨论】:

  • 您的真实数据在逗号前是否有空格(例如在您的“Jason ,Jason”条目中)或者这只是一个错字?
  • 实际上我在所有值中都有空间..让我更新问题

标签: python-3.x pandas unique


【解决方案1】:

我不知道有任何内置的 Pandas 函数可以做到这一点,所以我想出了一个使用 applymap 和一个自定义函数的解决方案,该函数用逗号分割,去除空格,并将独特的元素重新连接在一起成一个字符串。它并不漂亮,而且可能效率不高,但它应该可以工作:

In [15]: df1.applymap(lambda x: x if ',' not in str(x) else ','.join(sorted(set(y.strip() for y in(x.split(','))))))
Out[15]: 
             name  reports       year
Cochice     Jason  4,5,6,7  2012,2016
Pima        Molly       24       2012
Santa Cruz   Tina       31       2013
Maricopa     Jake        2       2014
Yuma          Amy        3       2014

编辑以显示仅应用于某个索引而不是所有行:

df1.loc[['Cochice']].applymap(lambda x: x if ',' not in str(x) else ','.join(sorted(set(y.strip() for y in(x.split(','))))))
Out[24]: 
          name  reports       year
Cochice  Jason  4,5,6,7  2012,2016

【讨论】:

  • 这行得通..只需再查询 1 个..这可以专门应用于特定的“索引”值而不是整个 df。在上述情况下Cochice
  • @Curious_Mind 谢谢!
猜你喜欢
  • 2021-06-17
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
相关资源
最近更新 更多