以下是我读取CSV文件的代码,但出错了我的代码有什么问题。
df2 = pd.read_csv(img_category_path, delim_whitespace= True, header=0, names=['category'], low_memory=False )
df['upper_lower'] = ['1' if i < 21 else '3' if i > 36 else '2' for i in df2['category']]
在我添加low_memory= False
时仍然出现错误
TypeError Traceback (most recent call last)
<ipython-input-146-e50367d03a63> in <module>
----> 1 df['upper_lower'] = ['1' if i < 21 else '3' if i > 36 else '2' for i in df2['category']]
<ipython-input-146-e50367d03a63> in <listcomp>(.0)
----> 1 df['upper_lower'] = ['1' if i < 21 else '3' if i > 36 else '2' for i in df2['category']]
TypeError: '<' not supported between instances of 'str' and 'int'
df2 = pd.read_csv(img_category_path, delim_whitespace= True, header=0, names=['category'], low_memory=False )
df['upper_lower'] = ['1' if i < 21 else '3' if i > 36 else '2' for i in df2['category']]
过滤文件以获得准确的结果
答案 0 :(得分:2)
您可以通过以下方法解决问题:
df['upper_lower'] = ['1' if i < 21 else '3' if i > 36 else '2' for i in df2['category']]
收件人:
df['upper_lower'] = ['1' if int(i) < 21 else '3' if int(i) > 36 else '2' for i in df2['category']]
出现问题(如注释中所指出的)是因为您从CSV文件中加载了表示数字的字符串,并且需要在比较之前将它们转换为int
(您的i
变量和{{1 }}系列的类型为df2["category"]
。