【问题标题】:How to return values from rows in a DataFrame column where certain conditions are met? [duplicate]如何从满足某些条件的 DataFrame 列中的行返回值? [复制]
【发布时间】:2021-03-29 13:33:57
【问题描述】:

我正在尝试定义一个函数,该函数将遍历数据框中现有列的每一行,并在满足某些条件时将其值写入同一行的新列:

def priceinspection(row): 
  if row["trend"] = "stronguptrend" or "strongdowntrend" or "superuptrend" or "superdowntrend" or "hyperuptrend" or "hyperdowntrend": 
    val = row["Close"] 
  else: 
    val = " " 
  return val

但val= row["Close"] 导致语法错误。我应该如何修复代码,以便在满足我的条件时返回“关闭”列值?

【问题讨论】:

  • 错误在上一行。使用== 进行相等检查,而不是=。并且多个or条件不能这样写,你需要单独做每个检查,或者像row["trend"] in ("stronguptrend", "strongdowntrend", ...)这样的东西。

标签: python pandas dataframe return-value


【解决方案1】:

这是一个简单的方法。

def priceinspection(df):

    new_column_list = []

    for row in df[['trend']].values:
        if row[0] == ("strongdowntrend" or "stronguptrend" or "superuptrend" or 
"superdowntrend" or "hyperuptrend" or "hyperdowntrend"):
            new_column_list.append("Close")
        else:
            new_column_list.append("")
        
    df['new_column'] = new_column_list
    return(df)

【讨论】:

    【解决方案2】:

    请根据条件进行布尔选择并使用np.where(condition, val if condition, val if not condition)。下面的例子。

    一些数据

    import pandas as pd
    df=pd.DataFrame({'trend':["stronguptrend" ,"strongdowntrend" ,"superuptrend", "superdowntrend" ,"hyperuptrend" , "hyperdowntrend"]})
    
    print(df)
    
           trend
    0    stronguptrend
    1  strongdowntrend
    2     superuptrend
    3   superdowntrend
    4     hyperuptrend
    5   hyperdowntrend
    

    解决方案

    import numpy as np
    df['Close']=np.where(df['trend'].isin(["stronguptrend","strongdowntrend"]),'val',"")
    print(df)
    
                 trend   Close
    0    stronguptrend   val
    1  strongdowntrend   val
    2     superuptrend      
    3   superdowntrend      
    4     hyperuptrend      
    5   hyperdowntrend     
    

    【讨论】:

      【解决方案3】:

      以下是我将如何使用我创建的任意条件来执行此操作。如果'stronguptrend 包含字符串'Fail',那么该表会将writestring 的值添加到新创建的“关闭”列中。

      如果条件不满足则只打印表格。

      df = pd.read_csv(".../ExcelFile.csv")
      df_filter= df[['stronguptrend','strongdowntrend','superuptrend',"superdowntrend", "hyperuptrend", "hyperdowntrend"]]
      if df_filter['stronguptrend'].str.contains('Fail').any():
          for index,row in df_filter.iterrows():
              writestring = ''
              df_filter.at[index, 'Close'] = writestring
          print(df_filter)
      else:
          print(df_filter)
      
      

      【讨论】:

        【解决方案4】:

        我意识到我犯了一个基本错误,当 == 是 python 中使用的符号时,我使用 = do 表示相等。感谢在问题 cmets 中回答的 bnaecker

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-23
          • 2020-07-16
          • 1970-01-01
          • 2022-12-08
          • 2020-05-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多