首页 > 解决方案 > 如何只显示与熊猫中另一个数据框共有的行?

问题描述

我试图只显示熊猫数据帧的行,这些数据帧的第一列与另一个数据帧中的另一行相同。这是我的代码:

sen_race.iloc(sen_race['Precinct'] == mi4['Precinct'])

如果有帮助,这里是数据框的照片:

mi4 数据框:https ://ibb.co/2qFMq4v

sen_race 数据框:https ://ibb.co/y4qBHG1

这是我得到的错误:

    ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-48-7695709c5335> in <module>
----> 1 sen_race.iloc(sen_race['Precinct'] == mi4['Precinct'])

/opt/anaconda3/lib/python3.7/site-packages/pandas/core/ops/common.py in new_method(self, other)
     62         other = item_from_zerodim(other)
     63 
---> 64         return method(self, other)
     65 
     66     return new_method

/opt/anaconda3/lib/python3.7/site-packages/pandas/core/ops/__init__.py in wrapper(self, other)
    519 
    520         if isinstance(other, ABCSeries) and not self._indexed_same(other):
--> 521             raise ValueError("Can only compare identically-labeled Series objects")
    522 
    523         lvalues = extract_array(self, extract_numpy=True)

ValueError: Can only compare identically-labeled Series objects

为什么它不起作用?

先感谢您!

标签: pythonpandasdataframe

解决方案


如果您只想过滤结果,则可以使用:

df = sen_race[sen_race['Precinct'].isin(mi4['Precinct'])]

推荐阅读