【问题标题】:Argument 'string' has incorrect type (expected str, got list)参数“字符串”的类型不正确(预期为 str,得到列表)
【发布时间】:2020-06-30 20:47:37
【问题描述】:

我有以下代码可以正常工作:

import spacy
import pandas as pd
import en_core_web_sm
nlp = en_core_web_sm.load()

text = [["Canada", 'University of California has great research', "non-location"],["China", 'MIT is at Boston', "non-location"]]
df = pd.DataFrame(text, columns = ['text', 'text2', 'text3'])

col_list = df.columns 
for col in col_list:
    df[col] = df[col].apply(lambda x: [[w.label_] for w in list(nlp(x).ents)])

df

但是,当我做同样的事情但有一个额外的数字列时,我收到错误:“Argument 'string' has wrong type (expected str, got list)”。

text = [["Canada", 'University of California has great research', "non-location", 2],["China", 'MIT is at Boston', "non-location", 3]]
df = pd.DataFrame(text, columns = ['text', 'text2', 'text3', 'text4'])

col_list = df.columns 

for col in col_list:
    df[col] = df[col].apply(lambda x: [[w.label_] for w in list(nlp(x).ents)])

我的问题是如何使它与整数一起工作或简单地忽略整数类型的数据列?

【问题讨论】:

  • 你能在不使用 pandas 的情况下简化这段代码来生成问题吗? (如果没有,添加pandas 标签而不是单独使用python 标签)。

标签: python pandas dataframe


【解决方案1】:

由于您自己编写对列的迭代,因此很容易排除 int 类型的列:

for col in col_list:
    if df[col].dtype == int:
        # ignore this column
        continue
    df[col] = df[col].apply(lambda x: [[w.label_] for w in list(nlp(x).ents)])

以下测试(而不是if df[col].dtype == int)将排除所有数字、布尔值...但不会检测object 类型的列,如字符串列:

if df[col].dtype != object

【讨论】:

  • 感谢您的回答!如果假设数据中有另一种数据类型“float”,我可以为第二行执行“if df[col].dtype == int and df[col].dtype == float:”吗?
  • or,当然不是and,但是可以,如果您只想排除 int 和 float ;) 有关更一般的测试,请参阅我的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多