Skip to main content
 首页 » 编程设计

python之或 Pandas 系列的关键字

2025年05月04日21虾米哥

我不明白如何在 pandas 系列中获得等同于 a = b or c 的东西。

MWE:

# basic python 
b = None 
c = 'not None' 
a = b or c 
assert a == c 
 
# expected behaviour in pandas 
df = pd.DataFrame({'b' : [None, 'not None'], 'c': ['not None', 'other']}) 
df.assign(a=lambda df: df.b | df.c) 
 
# raise TypeError: unsupported operand type(s) for |: 'str' and 'bool' 

请您参考如下方法:

使用 bfill 如果你有超过两列

df['a']=df.bfill(1).b 
df 
Out[16]:  
          b         c         a 
0      None  not None  not None 
1  not None     other  not None