【问题标题】:Replace cells in row if condition met如果满足条件,则替换行中的单元格
【发布时间】:2016-06-29 13:26:22
【问题描述】:

有没有办法为 Less, Middle Greater 列。如果大于0就将ROW换成1。那么顶行就变成了?

                  Conc      Less    Middle   Greater
Date                                                
2005-03-02 00:00  10.3  0.000000  1         1

这是原版

                  Conc      Less    Middle   Greater
Date                                                
2005-03-02 00:00  10.3  0.000000  0.083333  0.916667

2005-03-02 01:00  14.1  0.000000  0.750000  0.250000

2005-03-02 02:00   7.0  0.000000  0.833333  0.166667

2005-03-02 03:00   7.0  0.000000  1.000000  0.000000

2005-03-02 04:00   7.2  0.000000  1.000000  0.000000

2005-03-02 06:00   6.6  0.333333  0.666667  0.000000

2005-03-02 07:00   6.6  0.416667  0.583333  0.000000

我试过了:

df.loc[df['Less']>0:]=1
df.loc[df['Less']==0:]=0

但它显示为红色并显示 False True(在正确的位置)并且: 数据类型:布尔,无,无)

我也试过:像这样循环:

for line in df['Less']:
    if df['Less'] >0:
        df['Less']=1

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以将loc 与布尔条件一起使用:

    In [250]:
    df.loc[df['Less'] > 0, 'Less'] = 1
    df
    
    Out[250]:
                         Conc  Less    Middle   Greater
    Date                                               
    2005-03-02 00:00:00  10.3   0.0  0.083333  0.916667
    2005-03-02 01:00:00  14.1   0.0  0.750000  0.250000
    2005-03-02 02:00:00   7.0   0.0  0.833333  0.166667
    2005-03-02 03:00:00   7.0   0.0  1.000000  0.000000
    2005-03-02 04:00:00   7.2   0.0  1.000000  0.000000
    2005-03-02 06:00:00   6.6   1.0  0.666667  0.000000
    2005-03-02 07:00:00   6.6   1.0  0.583333  0.000000
    

    df.loc[df['Less']>0:] 语法无效,您想使用逗号并传递感兴趣的列名列表

    您的for 循环版本:

    for line in df['Less']:
        if df['Less'] >0:
            df['Less']=1
    

    无效,因为if 不理解如何解释布尔值数组,因此会出现错误,如果您执行了if (df['Less'] >0).all()if (df['Less'] >0).any(),那么它会很高兴,但无论如何它都没有意义'正在逐行迭代,然后测试整个 df,这是浪费的。

    【讨论】:

    • 干杯,这似乎奏效了啊,好吧,我用 .any() 试过了,但假设整个 df 都是真的,即使只有一个是真的。
    【解决方案2】:

    一次性完成:

    columns = ['Less', 'Middle', 'Greater']
    df[columns] = np.where(df[columns] >0, 1 ,0)
    

    或者单独做(注意选择列的双括号):

    df[['Less']] = np.where(df[['Less']] >0, 1 ,0)
    df[['Middle']] = np.where(df[['Middle']] >0, 1 ,0)
    df[['Greater']] = np.where(df[['Greater']] >0, 1 ,0)
    

    【讨论】:

    • np 是 numpy 导入 btw
    猜你喜欢
    • 2013-11-15
    • 2021-12-22
    • 1970-01-01
    • 2021-12-05
    • 2018-08-24
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多