Pandas中的字符串清理问题

时间:2014-04-14 20:59:49

标签: python pandas

我有一个pandas列,其中包含用引号,括号或任何内容包围的单词行,如下所示:

"cxxx"
[asdfasd]
asdfasdf
[asdf]
"asdf"

我的问题是,下面的代码正在从没有引号或括号的元素中剥离第一个和最后一个字符,我不知道为什么。

def keyword_cleanup(x):
    if "\"" or "[" in x:
        return x[1:-1]
    else:
        return x


csv["Keyword"] = csv["Keyword"].apply(keyword_cleanup)

1 个答案:

答案 0 :(得分:3)

if "\"" or "[" in x:

应该是

if "\"" in x or "[" in x:    # x must contain a left bracket or double-quote.

if x.startswith(('"', '[')): # x must start with a left-braket or double-quote

因为Python将前者解析为

if ("\"") or ("[" in x):

由于in运算符绑定比or更紧密。 (见Python operator precedence。)

由于任何非空字符串(例如"\"")都具有布尔值True,因此if-statement的条件始终为True,这就是为什么 keyword_cleanup始终返回x[1:-1]


但是,请注意,熊猫有string operators builtin。使用它们比使用apply为系列中的每个项目调用自定义Python函数要快得多。

In [136]: s = pd.Series(['"cxxx"', '[asdfasd]', 'asdfasdf', '[asdf]', '"asdf"'])

In [137]: s.str.replace(r'^["[](.*)[]"]$', r'\1')
Out[137]: 
0        cxxx
1     asdfasd
2    asdfasdf
3        asdf
4        asdf
dtype: object

如果你想从每个字符串的两端去掉所有括号或双引号,你可以改为使用

In [144]: s.str.strip('["]')
Out[144]: 
0        cxxx
1     asdfasd
2    asdfasdf
3        asdf
4        asdf
dtype: object