2017-10-17 70 views
2

我有一个熊猫数据框如下:大熊猫条件逻辑与混合dtypes

foo bar 
a b 
1 10 
2 25 
3 9 

我想添加一个新列如下:

foo bar baz 
a b 0 
1 10 1 
2 25 1 
3 9 1 

那就是: 如果行['富']或行[' 巴]是数字,然后行[ '巴兹'] = 1否则为0

什么我到目前为止是:

def some_function(row): 
    if row['foo']>=0 or row['bar']>=0: 
     return 1 
    return 0 

df['baz'] = df.apply(lambda row: some_function(row), axis=1 

但这不起作用,因为dtype不是int。 我不能删除non-int行,因为我需要它们在数据框中。

任何想法如何解决这个问题?

回答

5

如果要检查数字保存为字符串使用to_numeric,然后用ge>=)比较和使用all进行检查,如果所有值都True每行:

df['baz'] = df.apply(pd.to_numeric, errors='coerce').ge(0).all(1).astype(int) 
print (df) 
    foo bar baz 
0 a b 0 
1 1 10 1 
2 2 25 1 
3 3 9 1 

或者,如果需要检查单独列:

df['baz'] = (pd.to_numeric(df['foo'], errors='coerce').ge(0) | 
      pd.to_numeric(df['bar'], errors='coerce').ge(0)).astype(int) 

感谢,零为检查数字解决方案:

df['baz'] = df.apply(pd.to_numeric, errors='force').notnull().all(1).astype(int) 

但是,如果数字与字符串需要比较type

df = pd.DataFrame({'foo': ['a', 1, 2, 3], 'bar': ['b', 10, 25, 9]}) 


df['baz'] = (df.applymap(type) == str).all(1).astype(int) 
print (df) 
    bar foo baz 
0 b a 1 
1 10 1 0 
2 25 2 0 
3 9 3 0 

详细信息:

print (df.applymap(type)) 
      bar   foo 
0 <class 'str'> <class 'str'> 
1 <class 'int'> <class 'int'> 
2 <class 'int'> <class 'int'> 
3 <class 'int'> <class 'int'> 
+0

需要用'df.apply(pd.to_numeric,错误= '力')NOTNULL ().all(1).astype(int)'也许。 – Zero

+0

@jezrael谢谢!任何想法如何检查'foo'或'bar'中的值是否大于等于5?并应用上述条件? – Kvothe

+0

更改'ge(5)' - '大于或等于' – jezrael