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

转换熊猫系列以进行整数比较的简单方法

  •  0
  • npross  · 技术社区  · 8 年前

    我有非常简单的。下面的代码,并希望选择所有具有最高的1_排名的团队。

    import pandas as pd
    table = pd.read_table('team_rankings.dat')
    table.head()
    
    rank    team    rating  highest_rank    highest_rating  
    0   1   Germany 2097    1   2205    
    1   2   Brazil  2086    1   2161    
    2   3   Spain   2011    1   2147    
    3   4   Portugal    1968    2   1991    
    4   5   Argentina   1967    1   2128
    
    type((table['highest_rank'])) 
    pandas.core.series.Series
    
    table.loc[(table['highest_rank']) < 2]
    

    然后给我一个

    TypeError: unorderable types: str() < int()
    

    2 回复  |  直到 8 年前
        1
  •  3
  •   Bharath M Shetty    8 年前

    使用者 pd.to_numeric 具有 errors ='coerce'

    df.loc[(pd.to_numeric(df['highest_rank'],errors='coerce')) < 2]
    

    输出:

      rank       team  rating  highest_rank  highest_rating
    0     1    Germany    2097             1            2205
    1     2     Brazil    2086             1            2161
    2     3      Spain    2011             1            2147
    4     5  Argentina    1967             1            2128
    
        2
  •  3
  •   mkastner    8 年前

    可以将“-”解析为NaN值。这可能会帮助你完成更多的未来任务。

    table = pd.read_table('team_rankings.dat', na_values="-")
    

    看见 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html