Skip to main content
 首页 » 编程设计

python之将不同的 Pandas 数据框与系列对象进行比较

2025年05月04日21emanlee

我有以下 pandas.core.series.Series:

Color 
Red      4 
Green    7 

还有以下多索引数据框。我的目标是通过检查数据框中的 Value 列是否小于 pandas.core 中的相应颜色值来在数据框中创建 Target 列。 series.Series 如果是这样则返回 1。例如,在第一行中,dataframe 中 Value 列中的值为 12,这比 pandas 系列对象中对应的匹配索引值 4 大,因此 Target 返回 0。

              Value    Target 
Color Animal        
Red   Tiger      12      0 
      Tiger      3       1 
Green Lion       6       1 
      Lion       35      0 

我的以下尝试得到一个 ValueError: Can only compare identically-labeled Series objects。

import pandas as pd 
import numpy as np 
x = pd.Series([4,7], index=['Red','Green']) 
x.index.name = 'Color' 
 
dt = pd.DataFrame({'Color': ['Red','Red','Green','Green'], 'Animal': ['Tiger','Tiger','Lion','Lion'],  'Value': [12,3,6,35]}) 
dt.set_index(['Color','Animal'], inplace=True) 
dt['Target'] = np.where(dt['Value'] < x ,1 ,0 ) 

请您参考如下方法:

使用 lt 代替运算符,并指定轴。

dt['Target'] = dt['Value'].lt(x, axis=0).astype(int) 
print (dt) 
              Value  Target 
Color Animal                
Red   Tiger      12       0 
      Tiger       3       1 
Green Lion        6       1 
      Lion       35       0 

lt = "小于"