如何为Pandas DataFrame动态创建不同长度的'&'过滤器

时间:2018-09-01 00:58:45

标签: python python-3.x pandas

代码用途:

根据输入(test_tuple和params)的长度(可以是不同的长度),从主DataFrame(df)生成已过滤的DataFrame(filtered_df)。可能有数百种过滤器组合。

发布原因:

我想说的是,这里的一切都可以产生预期的输出。话虽这么说,我不喜欢解决方案1的实现方法,在该方法中,在dict中创建了一个虚拟DataFrame对象,该对象依次循环过滤和更新。解决方案1似乎有点模糊,但是我需要一些指导以实现更简洁的方法。

请求:

有没有办法使用解决方案2所示的filter_t?

filter_t的格式正确,但是是字符串。是否有产生filter_t的方法,以便可以如图所示使用它?

输入示例:

test_tuple = [('Serial Number', [12345]),
              ('Test Points', ['TestpointA', 'TestpointC']),
              ('Voltage_1', [3.0, 3.3, 3.6, 0.0]),
              ('Temperature Setpoint', [0, 60]),
              ('Slew_1', [200, 400, 800, 1600, 3200, 6400])]
params = ['sn', 'tp', 'v1', 'temp', 'slew']

代码:

for i in itertools.product(*[b for _, b in test_tuple]):
     print('\n'.join(f'{a}:{b}' for a, b in zip(params, i)))
     name_params = '_'.join(f'{b}{a}' for a, b in zip(params, i)) 
     filter_t = ' & '.join(f'(self.df["{c[0]}"] == {b})' for b, c in zip(i, test_tuple))
     print(f'filter_t: {filter_t}')
     filter_l = [(c[0], b) for b, c in zip(i, test_tuple)]

filter_t的格式为字符串:

filter_t: (self.df["Test Points"] == 3P3V) & (self.df["Slew_1"] == 5000)
filter_t: (self.df["Serial Number"] == 2450) & (self.df["Test Points"] == 3P3V) & (self.df["Voltage_1"] == 11.6) & (self.df["Temperature Setpoint"] == 25.0) & (self.df["Slew_1"] == 5000)

filter_l的格式:

filter_l: [('Test Points', '3P3V_Edge'), ('Slew_1', 200)]
filter_l: [('Serial Number', 1234), ('Test Points', '3P3V'), ('Voltage_1', 11.6), ('Temperature Setpoint', 25.0), ('Slew_1', 200)]

解决方案1-正常运行:

filtered_df = {1: df}
for x in filter_l:
     filtered_df[1] = (filtered_df[1].loc[(filtered_df[1][f'{x[0]}'] == x[1])])

解决方案2-可能吗?:

df_filter = self.df.loc[filter_t]

过滤器示例:

df_filter = self.df.loc[(self.df['Serial Number'] == 1234) &
                        (self.df['Test Points'] == '3P3V') &
                        (self.df['Voltage_1'] == 11.6) &
                        (self.df['Temperature Setpoint'] == 25.0) &
                        (self.df['Slew'] == 200)]

最终解决方案@John Zwinck-Thx:

filter_t = ' & '.join(f'{c[0]} == "{b}"' for b, c in zip(i, test_tuple))
filtered_df = df.loc[df.eval(filter_t)]

print(f'filter_t: {filter_t}')
>>> filter_t: Test_Points == "3P3V" & Slew_1 == "5000"

提前感谢您的建议。

1 个答案:

答案 0 :(得分:1)

如果可以安装numexpr,建议您尝试DataFrame.query()

首先,您需要在列名称中用下划线(或什么都没有)替换空格。然后,构建并使用如下所示的过滤器字符串:

filter_str = 'Serial_Number == 2450 and Test_Points == "3P3V" and Voltage_1 == 11.6'
df_filter = df.query(filter_str)

如果您安装了numexpr,这可能是最快的解决方案。

或者,构建一个蒙版列表,然后将其组合。这类似于但优于解决方案1:

masks = [df[x[0]] == x[1] for x in filter_l] # list of bool arrays
filtered_df = df[np.logical_and.reduce(masks)] # combine and apply masks