Python Pandas:如何使列中的字符串唯一

Python Pandas: How to unique strings in a column

我有一个 table 这样的:

col1 col2
ben US-US-Uk
Man Uk-NL-DE
bee CA-CO-MX-MX

我怎样才能使第 2 列中的值唯一,这意味着有一个像这样的 table?

col1 col2
ben US-Uk
Man Uk-NL-DE
bee CA-CO-MX

我已经试过了:

a.cc.str.split('-').unique()

但出现以下错误:

TypeError: unhashable type: 'list'

有人知道怎么做吗?

试试这个

col2 = 'CA-CO-MX-MX'
print '-'.join(set(col2.split('-')))

您可以使用 apply 调用 lambda 函数来拆分字符串,然后连接唯一值:

In [10]:

df['col2'] = df['col2'].apply(lambda x: '-'.join(set(x.split('-'))))
df
Out[10]:
  col1      col2
0  ben     Uk-US
1  Man  Uk-NL-DE
2  bee  CA-CO-MX

另一种方法:

In [22]:

df['col2'].str.split('-').apply(lambda x: '-'.join(set(x)))

Out[22]:
0       Uk-US
1    Uk-NL-DE
2    CA-CO-MX
Name: col2, dtype: object

计时

In [24]:

%timeit df['col2'].str.split('-').apply(lambda x: '-'.join(set(x)))
%timeit df['col2'] = df['col2'].apply(lambda x: '-'.join(set(x.split('-'))))
1000 loops, best of 3: 418 µs per loop
1000 loops, best of 3: 246 µs per loop

我喜欢。但是重新排序这些值是令人不安的。它会使人工目视检查和机械比较变得更加困难。

不幸的是,Python 没有有序集,这将是这里的完美工具。所以:

def unique(items):
    """
    Return unique items in a list, in the same order they were
    originally.
    """
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            result.append(item)
            seen.add(item)
    return result

df.col2 = df.col2.apply(lambda x: '-'.join(unique(x.split('-'))))

另一种创建有序集的方法是 OrderedDict:

from collections import OrderedDict

def u2(items):
    od = OrderedDict.fromkeys(items)
    return list(od.keys())

然后您可以使用 u2 而不是 unique。无论哪种方式,结果都是:

  col1      col2
0  ben     US-Uk
1  Man  Uk-NL-DE
2  bee  CA-CO-MX