【问题标题】:New column on Pandas with an if statmentPandas 中带有 if 语句的新列
【发布时间】:2021-06-05 00:25:04
【问题描述】:

我正在尝试重新创建表格的蓝色一侧,其中 excel 上 dnvgl 形状的方程式为 (=IF('LENGTH (m)'>(3*DEPTH d (m)),"Flat Long shaped","Box/round shaped").

我尝试使用这个公式在 pandas 上执行此操作。

liftinput['DNVGL Shape']= ('Flat Long Shaped' if liftinput['LENGTH (m)'] > (3*liftinput['DEPTH d (m)']) else 'Box/Round Shaped')

我收到此错误 - '系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。'

【问题讨论】:

  • 你在找liftinput['DNVGL Shape']= liftinput.apply(lambda x: 'Flat Long Shaped' if x['LENGTH (m)'] > (3*x['DEPTH d (m)']) else 'Box/Round Shaped', axis=1)
  • 请避免使用apply(...) stackoverflow.com/questions/54432583/…

标签: python excel pandas if-statement valueerror


【解决方案1】:

你要找的是这个;

import numpy as np

liftinput['DNVGL Shape'] = np.where(liftinput['LENGTH (m)'].gt(liftinput['DEPTH d (m)'].mul(3)), 'Flat Long Shaped', 'Box/Round Shaped')

这可能是您尝试做的最有效的方式。

【讨论】:

  • 这行得通。但是我们可以在 pandas 上做到这一点而不会出现值错误吗?
  • 您会收到值错误,因为您尝试在带有多个布尔值的括号内返回单个值。 (liftinput['LENGTH (m)'] > (3*liftinput['DEPTH d (m)'])pandas.Series 对象中返回大量Falses 和Trues。)你可以做的是类似liftinput['DNVGL Shape'] = ['Flat Long Shaped' if liftinput['LENGTH (m)'][idx] > (3*liftinput['DEPTH d (m)'][idx]) else 'Box/Round Shaped' for idx in liftinput.index]。但同样,这不是在大型数据集中使用的方法。
猜你喜欢
  • 2020-03-03
  • 2017-02-11
  • 1970-01-01
  • 2015-03-06
  • 2012-01-27
  • 2016-08-15
  • 2014-10-26
  • 2018-02-20
  • 2018-09-27
相关资源
最近更新 更多