【问题标题】:Get value in other cell in same row when if condition in for loop is met如果满足 for 循环中的条件,则在同一行中的其他单元格中获取值
【发布时间】:2021-09-30 17:29:15
【问题描述】:

我想遍历数据框列,当达到特定值时,我想将值保存在我创建的另一列中,并在同一行中称为“索引”。这是一个例子df:

index  value
  0      a
  2      b
  3      c
  9      a
  23     d

我尝试这样编写代码:

for value in df["value"]:
    if value == "a":
       current_index = #get value in "index" in current row

我不能简单地保存值为“a”的行的所有索引,因为那时我的其余代码将无法工作。

我认为这应该很容易,但不知何故我找不到解决方案。

感谢大家的支持!

【问题讨论】:

    标签: python pandas loops indexing


    【解决方案1】:

    IIUC:

    尝试通过布尔掩码和 loc 访问器:

    out=df.loc[df['value'].eq('a'),'index'].tolist()
    

    out的输出:

    [0, 9]
    

    如果你想创建一个列,那么:

    df['newcol']=df['index'].where(df['value'].eq('a'))
    

    df的输出:

        index   value   newcol
    0   0       a       0.0
    1   2       b       NaN
    2   3       c       NaN
    3   9       a       9.0
    4   23      d       NaN
    

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 2020-02-20
      • 2018-12-13
      相关资源
      最近更新 更多