“循环”;“我为我在……”;如果Python中满足另一个条件

“循环”;“我为我在……”;如果Python中满足另一个条件,python,loops,Python,Loops,我有一个充满各种价格特征(开放、封闭、高、低、开放-关闭等)的数据框架 我试图计算列“High Open”的平均值,但仅限于列“Open Close”中的值大于某个值(称之为“cents_diff”)的行 代码可以工作,但给出了错误的值。你知道怎样才能优雅地完成吗?谢谢 mean([j for j in temp['high-open'] for i in temp['open-close'] if i > cents_diff]) 如果您已经有一个Pandas数据帧,那么您也可以利用P

我有一个充满各种价格特征(开放、封闭、高、低、开放-关闭等)的数据框架

我试图计算列“High Open”的平均值,但仅限于列“Open Close”中的值大于某个值(称之为“cents_diff”)的行

代码可以工作,但给出了错误的值。你知道怎样才能优雅地完成吗?谢谢

mean([j for j in temp['high-open'] for i in temp['open-close'] if i > cents_diff])

如果您已经有一个Pandas数据帧,那么您也可以利用Pandas函数。现在看来,类似这样的东西会起作用:

temp.where(temp['open-close']>cents_diff]['high-open'].平均值()

也就是说,根据条件选择行,从中选择一列(
['high-open']
),并取其平均值(
.mean()
)。

如果您能够使用pandas,则无需遍历值。您可以使用内置函数,如: 平均值(self,axis=None,skipna=None,level=None,numeric_only=None,**kwargs)

这将返回所请求轴的平均值

例如:

 # importing pandas as pd 
 import pandas as pd 

 # Creating the dataframe  
 df = pd.DataFrame({"A":[12, 4, 5, 44, 1], 
                    "B":[5, 2, 54, 3, 2],  
                    "C":[20, 16, 7, 3, 8], 
                    "D":[14, 3, 17, 2, 6]}) 

  # Print the dataframe 
  df 

  # Get mean
  df.mean(axis = 0) 

  # or skip the Na values while finding the mean
  df.mean(axis = 1, skipna = True) 

欢迎来到StackOverflow。看见在您发布MRE代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您指定的问题。如在Pandas DataFrame中一样?将其作为
for
-循环的普通
写入,然后您可以添加
print()
以查看变量中的值。如果您将其作为
DataFrame
使用其函数,而不使用循环。-类似这样:
temp[temp['open-close']>cents_diff]['high-open'].mean()