带有混合dtypes的pandas条件逻辑

Kvo*_*the 2 python pandas

我有一个pandas数据帧如下:

foo bar
a   b
1   10
2   25
3   9
Run Code Online (Sandbox Code Playgroud)

我想添加一个新列,如下所示:

foo bar baz
a   b   0
1   10  1
2   25  1
3   9   1
Run Code Online (Sandbox Code Playgroud)

这是:如果row ['foo']或row ['bar]是数字,那么row ['baz'] = 1 else 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
Run Code Online (Sandbox Code Playgroud)

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

知道如何解决这个问题吗?

jez*_*ael 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
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢,Zero用于检查数字的解决方案:

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

但如果数字与字符串是必要的比较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
Run Code Online (Sandbox Code Playgroud)

详情:

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'>
Run Code Online (Sandbox Code Playgroud)