gpt4 book ai didi

python - 类型错误 : Could not compare type with Series

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:16 24 4
gpt4 key购买 nike

当我尝试使用字符串过滤 Dataframe 时出现以下错误

TypeError: Could not compare <type 'str'> type with Series

这是我的代码;

data = pd.read_csv('data.csv')
fildata = data[(data['cat1'] == 'FALSE') & (data['cat2'] != '') & (data['cat3'] == 'FALSE')]

编辑 1:

这是数据的样子;

count,word,cat1,cat2,cat3
1021,.,FALSE,,FALSE
825,the,TRUE,the,FALSE
693,and,TRUE,and,FALSE
647,of,TRUE,of,FALSE
646,",",FALSE,,FALSE
435,to,TRUE,to,FALSE
353,will,TRUE,will,FALSE
297,in,TRUE,in,FALSE
274,be,TRUE,be,FALSE

编辑 2:

但是为什么这样行得通呢?

data1 = pd.DataFrame({'cat1':[1,2,3,4],'cat2':[2,3,1,4],'cat3':[3,1,2,4]})

fildata = data1[(data1['cat1'] == 1) & (data1['cat2'] != 0) & (data1['cat3']== 3)]

这导致;

cat1 cat2 cat3
0 1 2 3

编辑 3:

我想问题出在类型上。 'cat1' & 'cat2' 属于 'bool' 类型

最佳答案

以下对我有用:

In [114]:

temp = """count,word,cat1,cat2,cat3
1021,.,FALSE,,FALSE
825,the,TRUE,the,FALSE
693,and,TRUE,and,FALSE
647,of,TRUE,of,FALSE
646,",",FALSE,,FALSE
435,to,TRUE,to,FALSE
353,will,TRUE,will,FALSE
297,in,TRUE,in,FALSE
274,be,TRUE,be,FALSE"""
data = pd.read_csv(io.StringIO(temp))
fildata = data[(data['cat1'] == False) & (data['cat2'].isnull() ) & (data['cat3'] == False)]
In [115]:

fildata
Out[115]:
count word cat1 cat2 cat3
0 1021 . False NaN False
4 646 , False NaN False

[2 rows x 5 columns]

您遇到的问题是字符串 FALSE/TRUEread_csv 解释的 bool 数据类型:

In [112]:

data.dtypes
Out[112]:
count int64
word object
cat1 bool
cat2 object
cat3 bool
dtype: object

所以你的比较应该针对这个类型而不是字符串 'FALSE'

关于python - 类型错误 : Could not compare <type 'str' > type with Series,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22985955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com