即使使用位运算符和适当的括号
我试图根据其某些列(本文Col1-4)详细阐述DF,并根据函数中定义的某些条件添加新列。 该代码可能比简单英语的解释更清楚:
def get_new_col(df):
if (df['col1'] == 0) | (df['col2'] == 0):
first_half = 0
else:
first_half = min(df['col1'], df['col2'])
if (df['col3'] == 0) | (df['col4'] == 0):
second_half = 0
else:
second_half = min(df['col3'], df['col4'])
return first_half + second_half
df['new_col'] = get_new_col(df)
我的问题是我得到了 valueerror:系列的真实价值是模棱两可的。使用A.Empty,A.Bool(),A.Item(),A.Any()或A.all()。
,即使我正确地(我认为?)语句并使用位运算符|代替或
,如此其他 thread 。
关于如何解决这个问题有什么想法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
iiuc,您需要
dataframe.apply
在行问题上,您遇到的是
df ['col1'] == 0
返回一个布尔序列,该系列无法通过如果语句。
使用
df.apply(get_new_col,axis = 1)
,我们只将数据框的一行传递到get_new_col
函数。要在没有
应用
的情况下执行相同的操作,您可以尝试IIUC, you need
DataFrame.apply
on rowsProblem you get is that
df['col1'] == 0
returns a boolean Series which couldn't be accepted byif
statement.With
df.apply(get_new_col, axis=1)
, we are only passing one row of dataframe toget_new_col
function.To do the same without
apply
, you can try