【问题标题】:optimising loop in pythonpython中的优化循环
【发布时间】:2018-01-13 16:02:24
【问题描述】:

我是 Python 新手。我正在尝试执行以下循环,并想知道我是否以正确的方式执行此操作,或者是否有更好(更快)的方式来执行此操作。简而言之,我想计算变量 y 的一系列条件均值。条件是针对 x 变量创建的。例如,df 中有 y x1 x2 x3 x4。第一组条件是 x1>x2 和 x1x2, x1

import pandas as pd
import numpy as np
import itertools

dates = pd.date_range('20130101', periods=100)

df = pd.DataFrame(np.random.randn(100,10), index=dates,                     
columns=list('ABCDEFGHIJ') )
df['y']=np.random.randn(100,1)

cols = list(df)
cols.insert(0, cols.pop(cols.index('y')))
df = df.loc[:, cols]

xlist = np.asarray(list(df.iloc[:,1:]))
xlist = pd.DataFrame(vlist, columns=['x'])

xcombo = pd.DataFrame(np.asarray(list(itertools.combinations(xlist['x'],     3))), columns=['x1','x2','x3'])
xcombo['stat'] = ""

for i, row in xcombo.iterrows():
    x1=(xcombo['x1'][i])
    x2=(xcombo['x2'][i])
    x3=(xcombo['x3'][i])
    # the following two lines (intends to) select subset of df meeting the         condition x1>x2 and x1<x3
    dfx = df[df[x1]>df[x2]]
    dfx = dfx[dfx[x1]<dfx[x3]] # df[df[x1]>df[x2] and df[x1]<df[x3]] doesn't work
    xcombo['stat'][i] = dfx['y'].mean() # store the mean value of y in the corresponding row        

【问题讨论】:

  • 我认为如果你描述你希望你的代码做什么而不是仅仅粘贴代码,你会得到更有用的响应。
  • 简单地说,我想计算变量 y 的一系列条件均值。条件是针对 x 变量创建的。例如,df 中有 y x1 x2 x3 x4。第一组条件是 x1>x2 和 x1x2、x1

标签: python pandas loops


【解决方案1】:

您可以使用 pandas 数据框的 itertuples() 方法。它比 iteritems() 或 iterrows() 快得多。

【讨论】:

  • 谢谢。使用 itertuples 时如何获取上述代码中的 i?
  • Itertuples 返回一个命名元组,您可以通过 row.Index 访问索引。
猜你喜欢
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 2015-07-24
  • 2017-02-21
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多