在数据帧中的前N行上起作用?

时间:2019-10-15 12:25:40

标签: python pandas

我需要遍历数据帧中的每一行,查看名为“ source_IP_address”的列,并查看前100行,以便我可以确定是否有任何行具有相同的“ source_IP_address”以及另一列指出“身份验证失败”。

我已经编写了一些执行此操作的代码,因为我无法使用Pandas在两列上滚动。问题是,速度不是很快,我想知道是否有更好的方法吗?

在前一个n行窗口中查找匹配轴值的数量以及属性列中的属性值的功能

def check_window_for_match(df_w, window_size, axis_col, attr_col, attr_var):     

l = []
n_rows = df_w.shape[0]

for i in range(n_rows):

    # create a temp dataframe with the previous n rows including current row
    temp_df = df_w.iloc[i-(window_size-1):i+1]

    #print(temp_df.shape)

    # assign the current 'B' value as the axis variable
    current_value = df_w[axis_col].iloc[i]

    #print(current_value)
    #print(temp_df)

    # given the temp dataframe of previous window of n_rows, check axis matches against fails
    l_temp = temp_df.loc[(temp_df[axis_col] == current_value) & (temp_df[attr_col] == attr_var)].shape[0]
    l.append(l_temp)

return l

例如

 df_test = pd.DataFrame({'B': [0, 1, 2, np.nan, 4, 6, 7, 8, 10, 8, 7], 'C': [2, 10, 'fail', np.nan, 6, 7, 8, 'fail', 8, 'fail', 9]})

df_test

matches_list = check_window_for_match(df_test, window_size=3, axis_col='B', attr_col='C', attr_var='fail')

输出:[0,0,1,0,0,0,0,1,0,2,0]

我想知道我的代码是否正确,这是执行此操作的最佳方法,还是有更好的选择。

0 个答案:

没有答案