2017-10-17 36 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