【问题标题】:How to combine two columns conditionally based on a third如何根据第三个有条件地组合两列
【发布时间】:2021-12-05 11:42:34
【问题描述】:

假设我有一个包含四列的 df,所有列都有一个共享的时间序列索引。我需要根据 column3 有条件地将 column1 和 column2 合并到一个新的 column4 中。我是python新手,直接跳到失败的for循环如下

for i in df.column3.index:
    if df.loc[i, "column1"] > 180:
        df.loc[i, "column4"] = df["column1"]
    elif df.loc[i, "column1"] < 180:
        df.loc[i, "column4"] = df["column2"]

我希望有人可以提出解决方案。 谢谢,

【问题讨论】:

    标签: python dataframe merge conditional-statements


    【解决方案1】:

    您不需要为此迭代每一行 - 通常情况就是这样。

    在这种情况下,您可以使用where。看看documentation

    并为您的示例尝试以下操作:

    df['column3'] = df.column1.where(df.index &gt; 180, df.column2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多