在 Pandas Dataframe 单元格中查找唯一值

Rah*_*wal 0 unique python-3.x pandas

样品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'])
Run Code Online (Sandbox Code Playgroud)

好像

                     name            ...                                   year
Cochice     Jason , Jason            ...              2012 , 2012 , 2016 , 2016
Pima                Molly            ...                                   2012
Santa Cruz           Tina            ...                                   2013
Maricopa             Jake            ...                                   2014
Yuma                  Amy            ...                                   2014
Run Code Online (Sandbox Code Playgroud)

我希望索引的每个单元格都有唯一的值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
Run Code Online (Sandbox Code Playgroud)

the*_*orm 5

我不知道任何内置的 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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)