在条件pandas上为新列分配值

时间:2017-10-26 10:40:59

标签: python pandas dataframe

我有一个数据框:

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

有没有更简单的方法可以不进行迭代?

2 个答案:

答案 0 :(得分:2)

条件转换为int - True s转换为1False转换为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

答案 1 :(得分: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
相关问题