【问题标题】:Translate Excel if condition from Excel to Python将 Excel if 条件从 Excel 转换为 Python
【发布时间】:2021-12-11 04:01:57
【问题描述】:

我正在尝试将 if 语句从 excel 转换为 python。

我知道对于 excel,我们有 If 语句:

IF(logical_test, [value_if_true], [value_if_false])

对于 IFERROR 语句,我们有:

IFERROR(value, value_if_error)

或函数:

The OR function returns TRUE if any of its arguments evaluate to TRUE, and returns FALSE if all of its arguments evaluate to FALSE.

对于 Python,我想复制以下两个 excel if 语句。

=IF( OR(IFERROR(AM2+0=0, AM2=""), DK2<>" "), " ", AM2)

这里AM2,DK2是excel文件中的列,在excel中表示不相等。

谁能帮我把它翻译成 Python,这让我很困惑。

【问题讨论】:

  • 你能补充一些例子吗?因为答案取决于您拥有哪些数据类型。特别是在AM2+0=0 的情况下。这是什么意思?有文字'0' 还是什么?
  • 您好 AM2 和 DK2 都是数字列,但有些值同时包含空白值和空格,因此请确认添加 0。
  • numpy.where,import numpy as np. np.where(, df['col1'], df['col2'])

标签: excel pandas dataframe numpy python-3.9


【解决方案1】:

类似这样的东西(如果我们谈论 pandas DataFrame):

df['whatever'] = np.where(
    (df['AM'] == 0) | (df['AM'].isna()) | (df['AM'] == " ") | (df['DK'] != ' ') | (df['AM'] == ""),
    "ZZZ",
    df['AM']
)

我使用字母作为列名,因为没有提供列名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 2014-11-19
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多