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

基于条件操纵行

  •  1
  • Make42  · 技术社区  · 6 年前

    method 如果 type 是一个侏儒:

    newcolumn = []
    for index, row in results_DF.iterrows():
        newcolumn.append('BBBB' if row['type'] is np.nan else row['method'])
    results_DF['method'] = pd.Series(newcolumn)
    

    这个实现看起来很难看。如何写得更好-更实用的风格?

    2 回复  |  直到 6 年前
        1
  •  1
  •   jezrael    6 年前

    使用 DataFrame.loc 使用由创建的布尔amsk Series.isna :

    results_DF.loc[results_DF['type'].isna(), 'method'] = 'BBBB'
    
    #oldier pandas versions
    #results_DF.loc[results_DF['type'].isnull(), 'method'] = 'BBBB'
    

    另一个解决方案 numpy.where

    results_DF['method'] = np.where(results_DF['type'].isna(), 'BBBB', results_DF['method'])
    

    或@Jon Clements的解决方案,谢谢:

    results_DF['method'] = results_DF.where(results_DF['type'].notnull(), 'BBBB')
    

    results_DF = pd.DataFrame({'method': ['a','s','d'],
                               'type':[np.nan, np.nan, 4]})
    
    print (results_DF)
      method  type
    0      a   NaN
    1      s   NaN
    2      d   4.0
    
    results_DF.loc[results_DF['type'].isna(), 'method'] = 'BBBB'
    print (results_DF)
      method  type
    0   BBBB   NaN
    1   BBBB   NaN
    2      d   4.0
    
        2
  •  1
  •   Mohamed Thasin ah    6 年前

    试试这个,

    mask=results_DF['type'].isnull()
    results_DF.loc[mask]='BBBB'