首页 > 解决方案 > Pandas:在列值中查找空格+不常用字符的最快方法是什么?

问题描述

在 Pandas 中,我有一列 col_one,最初在每个单元格中包含逗号分隔的值。

['a, b, e, g, o', 'a, b, d', 'a, b, c, f, g', 'a, b, c, f', 'a, c, e', 'a, b, c, o', 'b, c, h, n', 'a, b, c, g, o', 'a, b, c, f', 'a, b, c, g, h, o', 'b', 'a, b, f, m', 'a, b, c, g, h', 'a, b, d, f, g', 'a, c, n', 'j', 'b, c, f', 'a, b, g, l', 'b', 'b', 'a, b, d, e ', 'a, b, c', 'a, b, e, g', 'a, b, c, d, f, g', 'd, k, l', 'a, b, c, f, g ', 'a, b, c, f', 'a, b, c, d,  g', 'b, d, e', 'b, d', 'a', 'b, o', 'c, o', 'b, c, o', 'c', 'a, g, i', 'b, c, n', 'a, b', 'b, c, o, n', 'b, c, h', 'a, b, c, f, g, h', 'a, b, c, d', 'a, b, d', 'a, e, g', 'a, b, c, e, g, k, m', 'b, c, o', 'a, b, f, k', 'd, l', 'a, b, l', 'a, b, c', 'a', 'c, d, g, l', 'b, d, e, o', 'b, d', 'a, b, c, d, e, f, o', 'b', 'a, b, c, f', 'b, c, g', 'b, c, g, k', 'a', 'c', 'b, c, o', 'b, c, n, o']

我曾经str.split(', ').explode().value_counts() .reset_index()数过单个字母。但是在结果表中,一些字母出现了两次,大概是因为字符串包含尾随空格。不幸的是,这些在结果表的 Jupyter Notebook 显示中不可见,因为它们只是空白。

使用这个

col_one_list = df["letter"].tolist()
print (col_one_list)

给了我所有计数值的列表。在这个列表中,我能够发现一个尾随空格(“g”)。但我怎么能做得更好呢?

['b', 'a', 'c', 'g', 'd', 'f', 'o', 'e', 'n', 'h', 'l', 'k', 'm', 'j', 'g ', ' g', 'e ', 'i']

标签: pythonpandasjupyter-notebookdata-cleaning

解决方案


您可以将空格替换为''然后继续 split-explode-value_counts,或者您也可以使用get_dummies

s.str.replace('\s+', '').str.get_dummies(',').sum()

输出:

a    36
b    49
c    35
d    15
e     9
f    13
g    18
h     5
i     1
j     1
k     4
l     5
m     2
n     5
o    13
dtype: int64

推荐阅读