【问题标题】:Greater than and less than function in pandaspandas 中的大于和小于函数
【发布时间】:2020-11-26 02:55:04
【问题描述】:

我正在测试“daychange”列中的数据。如果值在一个范围内,我希望单独的列显示 100 表示是,0 表示否。我试过这段代码:

cond16 = df[(df['daychange']<8) & (df['daychange']>2)]
df['day3'] = np.where(cond16, 100, 0)

但是得到以下错误:

ValueError: Length of values (932) does not match length of index (13063)

我们将不胜感激!

【问题讨论】:

  • 您已经选择了数据,只需使用条件:cond16 = (df['daychange']&lt;8) &amp; (df['daychange']&gt;2)

标签: pandas numpy dataframe conditional-statements


【解决方案1】:

你几乎明白了。 @Erfan 在 cmets 提到了这个小错误。您只需要条件,而不是 np.where 中的选择。

cond16 = (df['daychange']<8) & (df['daychange']>2)
df['day3'] = np.where(cond16, 100, 0)

【讨论】:

    【解决方案2】:

    正如 Erfan 在评论中提到的,您已经创建了过滤器。只需使用它来设置 DataFrame 中的值。

    # Create filter condition
    cond16 = (df['daychange']<8) & (df['daychange']>2)
    
    # Set rows where condition is true to 100
    df.loc[cond16, 'day3'] = 100
    
    # Set rows where condition is not true to 0
    df.loc[~cond16, 'day3'] = 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多