【问题标题】:Applying a conditional statement to all value of a dataframe将条件语句应用于数据框的所有值
【发布时间】:2017-09-08 17:25:35
【问题描述】:

我有一个包含多个列和索引的数据框,如果值为正,我想将每个值替换为 1,否则替换为 -1。
这是我尝试执行的方法,但失败了,并且出现以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

还有很多其他帖子有同样的错误,但我读过的没有一个有帮助。

这是我的代码:

        numeric_cols = [col for col in df1 if df1[col].dtype.kind != 'O']
        if df1[numeric_cols] > 0:
            df1[numeric_cols] = 1
        else:
            df1[numeric_cols] = -1

【问题讨论】:

    标签: python pandas if-statement dataframe


    【解决方案1】:

    df1[numeric_cols] 为您提供数据集中所有行的 numeric_cols,因此您无需逐行查看数据。

    df1[numeric_cols] = df1[numeric_cols].apply(lambda x : 1 if x > 0 else -1) 
    

    应该可以。

    类似于Replace an entry in a pandas DataFrame using a conditional statement

    【讨论】:

      【解决方案2】:

      .apply 会很慢。你打赌只做两个操作:

      df = pd.DataFrame([[1,2,3],[1,5,2],[2,3,1]])
      print df
      
         0  1  2
      0  1  2  3
      1  1  5  2
      2  2  3  1    
      
      df[df<3]=0
      df[df>=3]=1
      
      print df
      
         0  1  2
      0  0  0  1
      1  0  1  0
      2  0  1  0
      

      【讨论】:

        猜你喜欢
        • 2014-02-08
        • 2019-10-15
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        • 2017-01-05
        • 2021-12-29
        • 2011-08-15
        相关资源
        最近更新 更多