代码之家  ›  专栏  ›  技术社区  ›  gibbz00

将不相同的数据帧与序列对象进行比较

  •  1
  • gibbz00  · 技术社区  · 8 年前

    pandas.core.series.Series :

    Color
    Red      4
    Green    7
    

    以及下面的多索引数据帧。我的目标是创造 Target Value 数据帧中的列小于 熊猫.core.series.系列 价值

                  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 )
    
    1 回复  |  直到 8 年前
        1
  •  5
  •   cs95 abhishek58g    8 年前

    使用 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
    

    书信电报 =“小于”