python Pandas : How to unique strings in a column

标签 python pandas ipython dataframe

我有一个这样的表:

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

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

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

我已经试过了:

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

但出现以下错误:

TypeError: unhashable type: 'list'

有人知道怎么做吗?

最佳答案

您可以使用 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 Pandas : How to unique strings in a column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29234661/

相关文章:

python - 带有日期时间的 Numpy 结构化数组

python - 合并 Pandas 2 DataFrame,具有不同的行数和列数

python - pandas 打印 `tput: unknown terminal "emacs"`

python - Pandas DataFrame 过滤 ||仅保留列的连续元素

python - 使用多个多索引级别删除

python - 从 C 调用 IPython.embed() 方法时为 "ValueError: call stack is not deep enough"

bash - ipython 语法颜色

python - 为什么安装 `pip install -e .`的包不需要__init__.py?

python - 如何使用上传图像的 permalink_public URL 将其包含在消息中?

python 3 : Most efficient way to create a [func(i) for i in range(N)] list comprehension