Python ValueError:只能比较带有相同标记的Series对象

时间:2018-01-04 10:27:13

标签: python pandas

我看到关于这个的叠加流量帖但是没有任何东西符合我的要求,所以我创建了这个帖子。我正在使用python 3.6。我有一个数据框df_student。示例数据如下图所示 enter image description here

我尝试使用以下代码过滤数据框

df_filter1=df_student.loc[(df_student['year'] == x & (df_student['Grade']==y) & (df_student['Mail']==z)]

x,y& z从代码生成,抱歉,我无法共享代码。但是在运行之后我收到了错误消息

ValueError: Can only compare identically-labeled Series objects

检查后,我发现x,y,z是单个值生成的'系列'对象.x,y& z也是我的数据框年中的str类型为int64类型,Grade&邮件是' O'类型。所以我修改了代码&使用以下代码

df_filter1=df_student.loc[(df_student['year'] == int(x.values[0]) & (df_student['Grade']==y.values[0]) & (df_student['Mail']==z.values[0])]

现在,我没有收到任何错误消息,但是df_filter1显示为一个空数据框,它应该有一些行。请建议我需要做哪些修改

我已完成以下修改 以色列的建议

df_filter1=df_student.loc[(df_student['year'] == x.astype(int).iat[0]) & 
                          (df_student['Grade']==y.iat[0]) & 
                          (df_student['Mail']==z.iat[0])]

但是收到错误消息

AttributeError: 'int' object has no attribute 'astype'

我根据jezrael的建议修改了代码&再次从我的csv文件重新加载数据&我的下一次运行中出现了这些错误

  File "<ipython-input-69-6c2be16ee93f>", line 6, in studQuery
    df_filter1=df_student.loc[(df_student['year'] == x) & (df_student['Grade']==y.iat[0]) & (df_student['Mail']==z.iat[0])]

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1964, in __getitem__
    return self._getitem_column(key)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1971, in _getitem_column
    return self._get_item_cache(key)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1645, in _get_item_cache
    values = self._data.get(item)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals.py", line 3590, in get
    loc = self.items.get_loc(item)

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2444, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1210, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1218, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'year'

1 个答案:

答案 0 :(得分:1)

您可以使用if-else语句检查值的类型是否为int

x = int(x) if isinstance(x, int) else int(x.iat[0])
df_filter1=df_student.loc[(df_student['year'] == x) & 
                          (df_student['Grade']==y.iat[0]) & 
                          (df_student['Mail']==z.iat[0])]