【问题标题】:removing non English words from df.columns从 df.columns 中删除非英语单词
【发布时间】:2019-08-03 18:09:03
【问题描述】:

我将多个数据集附加在一起,不幸的是,在数据收集中,一些数据收集器将翻译添加到英语问题中。

df['What is your name'] 在其他数据集中报告为 df['What is your name Como te llamas']

理想情况下,我只想要 df['What is your name']

姓名列和许多其他列(年龄、住房等)一样。

我正在使用 nltk 使用以下代码去除列名中的所有非英文单词:

df_t.columns = " ".join(w for w in nltk.wordpunct_tokenize(df_t.columns) 
    if w.lower() in words or not w.isalpha())

但我得到以下错误错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-65a4c079ba1a> in <module>()
     34     df_t['File Name'] = df_t['File Name'].str.strip().str[-30:]
     35     df_t.columns = df_t.columns.str.replace(r'(^.*female.*$)', 'n_female_workers')
---> 36     df_t.columns = " ".join(w for w in nltk.wordpunct_tokenize(df_t.columns) if w.lower() in words or not w.isalpha())
     37 
     38     list_month.append(df_t)

~\Anaconda3\lib\site-packages\nltk\tokenize\regexp.py in tokenize(self, text)
    129         # If our regexp matches tokens, use re.findall:
    130         else:
--> 131             return self._regexp.findall(text)
    132 
    133     def span_tokenize(self, text):

TypeError: expected string or bytes-like object

如何解决?

【问题讨论】:

  • nltk.wordpunct_tokenize 需要一个 str 对象作为参数,你传递给它一个 pd.Series
  • 是的,我觉得是这样,你知道如何更正代码吗?
  • jezrael 不幸的是它返回了同样的错误..

标签: python pandas nltk


【解决方案1】:

我认为您需要按列名称循环以将标量 string 传递给 wordpunct_tokenize 函数:

df_t = pd.DataFrame(columns=['What is your name Como te llamas'])

words = ['what','is','your','name']
df_t.columns = [" ".join(w for w in nltk.wordpunct_tokenize(x) 
                       if w.lower() in words or not w.isalpha()) 
                       for x in df_t.columns]
print (df_t)
Empty DataFrame
Columns: [What is your name]
Index: []

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多