使用替换为pandas的列df TypeError:无法比较类型&n; ndarray(dtype = int64)'和' str'

时间:2017-12-03 18:21:53

标签: python pandas csv dataframe

我该如何解决这个问题?

import pandas as pd                                                                        

csv_file = 'sample.csv'                                                                    
count = 1                                                                                  
my_filtered_csv = pd.read_csv(csv_file, usecols=['subDirectory_filePath', 'expression'])   

emotion_map = { '0':'6', '1':'3', '2':'4', '3':'5', '4':'2', '5':'1', '6':'0'}             

my_filtered_csv['expression'] = my_filtered_csv['expression'].replace(emotion_map)         

print(my_filtered_csv)                                                                     

错误是:

Traceback (most recent call last):
  File "/Users/mona/CS585/project/affnet/emotion_map.py", line 11, in <module>
    my_filtered_csv['expression'] = my_filtered_csv['expression'].replace(emotion_map)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/generic.py", line 3836, in replace
    limit=limit, regex=regex)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/generic.py", line 3885, in replace
    regex=regex)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 3259, in replace_list
    masks = [comp(s) for i, s in enumerate(src_list)]
  File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 3259, in <listcomp>
    masks = [comp(s) for i, s in enumerate(src_list)]
  File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 3247, in comp
    return _maybe_compare(values, getattr(s, 'asm8', s), operator.eq)
  File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 4619, in _maybe_compare
    raise TypeError("Cannot compare types %r and %r" % tuple(type_names))
TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'

Process finished with exit code 1

csv文件的几行如下:

,subDirectory_filePath,expression
0,689/737db2483489148d783ef278f43f486c0a97e140fc4b6b61b84363ca.jpg,1
1,392/c4db2f9b7e4b422d14b6e038f0cdc3ecee239b55326e9181ee4520f9.jpg,0
2,468/21772b68dc8c2a11678c8739eca33adb6ccc658600e4da2224080603.jpg,0
3,944/06e9ae8d3b240eb68fa60534783eacafce2def60a86042f9b7d59544.jpg,1
4,993/02e06ee5521958b4042dd73abb444220609d96f57b1689abbe87c024.jpg,8
5,979/f675c6a88cdef99a6d8b0261741217a0319387fcf1571a174f99ac81.jpg,6
6,637/94b769d8e880cbbea8eaa1350cb8c094a03d27f9fef44e1f4c0fb2ae.jpg,9
7,997/b81f843f08ce3bb0c48b270dc58d2ab8bf5bea3e2262e50bbcadbec2.jpg,6
8,358/21a32dd1c1ecd57d3e8964621c911df1c0b3348a4ae5203b4a243230.JPG,9

2 个答案:

答案 0 :(得分:1)

将emotion_map更改为以下内容解决了问题:

<head>

答案 1 :(得分:0)

另一种可能也会造成此错误的可能性是: 您已经运行了一次此代码并且数据已经被替换。

要解决这个问题,可以回去重新加载数据集