【问题标题】:Assign values in new column on condition pandas在条件熊猫的新列中分配值
【发布时间】:2017-10-26 10:40:58
【问题描述】:

我有一个数据框:

id    name    value
 1    asd      0.5
 2    fgg      0.8
 3    hfd      1.5
 4    erw      0.5

我必须创建一个新列 accept,这样,如果值大于 1.0,则将 outlier 设为 1,否则设为 0。

id    name    value   accept
 1    asd      0.5      0
 2    fgg      0.8      0
 3    hfd      1.5      1
 4    erw      0.5      0

我可以使用 iterrows 并使用 .loc。

for index,row in df.iterrows():
    if row['value']>1:
        df.loc[df.index==row.index,'accept'] = 1
    else:
        df.loc[df.index==row.index,'accept'] = 0

有没有更简单的方法来做到这一点而无需迭代?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    条件转换为int - Trues 转换为1Falses 转换为0

    df['accept'] = (df['value'] > 1).astype(int)
    print (df)
       id name  value  accept
    0   1  asd    0.5       0
    1   2  fgg    0.8       0
    2   3  hfd    1.5       1
    3   4  erw    0.5       0
    

    对于其他值,请使用 numpy.where:

    df['accept'] = np.where(df['value'] > 1, 'high', 'low')
    print (df)
       id name  value accept
    0   1  asd    0.5    low
    1   2  fgg    0.8    low
    2   3  hfd    1.5   high
    3   4  erw    0.5    low
    

    【讨论】:

      【解决方案2】:

      只要您的值介于 0 和 2 之间,请使用 np.floor + astype(int)

      df['accept'] = np.floor(df.value).astype(int)
      df
      
         id name  value  accept
      0   1  asd    0.5       0
      1   2  fgg    0.8       0
      2   3  hfd    1.5       1
      3   4  erw    0.5       0
      

      【讨论】:

        猜你喜欢
        • 2019-03-14
        • 1970-01-01
        • 2018-05-24
        • 2021-09-22
        • 2023-02-15
        • 1970-01-01
        • 2017-12-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多