ValueError:只能比较带有相同标签的系列对象Python Pandas

2024-06-16 17:03:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧:

FB7=

Date/Time   |Ticker |Gia today
0   2020-02-01  |CTF    |23.50
2   2020-02-01  |PXL    |8.40
3   2020-02-01  |DBC    |20.52
4   2020-02-01  |TCH    |32.42
5   2020-02-01  |DRC    |22.28
6   2020-02-01  |HSG    |7.80
8   2020-02-01  |KOS    |27.90
9   2020-02-01  |SBT    |18.02
11  2020-02-01  |MPC    |19.70
13  2020-02-01  |NKG    |7.38
15  2020-02-01  |HPG    |19.63

FB8=
    Date/Time   |Ticker |Gia today
1568    2020-07-01  |HPG    |19.39
1631    2020-07-01  |MPC    |20.40
1724    2020-07-01  |CTF    |21.70
1786    2020-07-01  |KOS    |28.00
1805    2020-07-01  |SBT    |18.11
1847    2020-07-01  |NKG    |7.73
1870    2020-07-01  |TCH    |33.20
1920    2020-07-01  |HSG    |7.55
1991    2020-07-01  |PXL    |8.30
2040    2020-07-01  |DBC    |20.52
2047    2020-07-01  |DRC    |23.07

我试着列出如下代码:

FB8[(FB8['Gia today'] >= FB7['Gia today']) & (FB8.Ticker == FB7.Ticker)]

这显示了错误:

" ValueError Traceback (most recent call last)
<ipython-input-64-222ec9c62682> in <module>()
      8 #FB8.set_index('Ticker')
      9 FB8
---> 10 FB8[(FB8['Gia today'] >= FB7['Gia today']) & (FB8.Ticker == FB7.Ticker)]
     11 
     12 

1 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/ops/__init__.py in wrapper(self, other)
    363 
    364         if isinstance(other, ABCSeries) and not self._indexed_same(other):
--> 365             raise ValueError("Can only compare identically-labeled Series objects")
    366 
    367         lvalues = extract_array(self, extract_numpy=True)

ValueError: Can only compare identically-labeled Series objects

我可以做什么来相同地标记序列对象


Tags: selftodaydatetimectfdbctickerother
1条回答
网友
1楼 · 发布于 2024-06-16 17:03:09

尝试在比较之前对列中的值进行排序。代码如下:

FB7.sort_values(by=["Ticker"], inplace=True, ignore_index=True)
FB8.sort_values(by=["Ticker"], inplace=True, ignore_index=True)

display(FB8[(FB8['Gia today'] >= FB7['Gia today'])])
display(FB7[(FB8['Gia today'] >= FB7['Gia today'])])

结果如下:

    Date/Time   Ticker  Gia today
1   2020-07-01  DBC     20.52
2   2020-07-01  DRC     23.07
5   2020-07-01  KOS     28.00
6   2020-07-01  MPC     20.40
7   2020-07-01  NKG     7.73
9   2020-07-01  SBT     18.11
10  2020-07-01  TCH     33.20

    Date/Time   Ticker  Gia today
1   2020-02-01  DBC     20.52
2   2020-02-01  DRC     22.28
5   2020-02-01  KOS     27.90
6   2020-02-01  MPC     19.70
7   2020-02-01  NKG     7.38
9   2020-02-01  SBT     18.02
10  2020-02-01  TCH     32.42

另外,请注意,在这种情况下,数据帧必须具有相同的形状

相关问题 更多 >