如何简单地遵循代码,Dataframe,迭代,for

时间:2016-05-24 09:49:25

标签: python pandas dataframe iteration

  1. 我将dadaframe命名为"数据"并希望简单地按照以下代码进行调整。
  2. 花了很多时间跑。解决这个问题有什么好的解决方案吗?

    for i in range(0,len(data)):
        if data['Theta'][i]<=np.pi/8 and data['Theta'][i]>=0: 
           data['Theta'][i]=0
        elif data['Theta'][i]<=3*np.pi/8 and data['Theta'][i]>1*np.pi/8: 
             data['Theta'][i] = np.pi/4
        elif data['Theta'][i]<=np.pi and data['Theta'][i]>3*np.pi/8: 
             data['Theta'][i] = np.arctan(2)
        elif data['Theta'][i]<=13*np.pi/8 and data['Theta'][i]>np.pi: 
             data['Theta'][i] = np.arctan(-2)
        elif data['Theta'][i] <= 15 * np.pi/8 and data['Theta'][i] >13*np.pi/8:
             data['Theta'][i] = -1*np.pi/4
        elif data['Theta'][i] >=15 * np.pi / 8 and data['Theta'][i] <= 2*np.pi:
             data['Theta'][i] = 0
    

2 个答案:

答案 0 :(得分:0)

如果为每个条件创建掩码,速度会更快:

data.loc[(data['Theta']<=np.pi/8) & (data['Theta']>=0), 'Theta'] = 0 data.loc[(data['Theta']<=3*np.pi/8) & (data['Theta']>1*np.pi/8), 'Theta'] = np.pi/4 
data.loc[(data['Theta']<=np.pi) & (data['Theta']>3*np.pi/8), 'Theta'] = np.arctan(2)
data.loc[(data['Theta']<=3*np.pi/8) & (data['Theta']>np.pi), 'Theta'] = np.arctan(-2) 
data.loc[(data['Theta']<=15*np.pi/8) & (data['Theta']>13*np.pi/8), 'Theta'] = -1*np.pi/4 
data.loc[(data['Theta']>=15*np.pi/8) & (data['Theta']<2*np.pi), 'Theta'] = 0

所以这使用loc和一个掩码,我们将df中的所有行与条件进行比较,这将返回一个掩盖整个df的布尔掩码,以便只更新满足条件的行。此外,我们必须使用&而不是and,因为您要比较数组而不是标量值。由于运算符优先级,我们还需要将条件包装在括号中。

答案 1 :(得分:0)

你可以定义一个你想要的功能,然后将它应用于所有行,它应该很快。

def f(x):
    if x <= np.pi / 8 and x >=0:
        x = 0
    elif x <= 3 * np.pi / 8 and x > 1 * np.pi / 8:
        x = np.pi / 4
    elif x <= np.pi and x > 3 * np.pi / 8:
        x = np.arctan(2)
    elif x <= 13 * np.pi / 8 and x > np.pi:
        x = np.arctan(-2)
    elif x <= 15 * np.pi / 8 and x > 13 * np.pi / 8:
        x = -1 * np.pi / 4
    elif x >= 15 * np.pi / 8 and x <= 2 * np.pi:
         x = 0
    return x

data["Theta"] = data["Theta"].apply(f)