Python Pandas - 是否可以与计数器一起运行dataframe.query方法

问题描述 投票:0回答:3

我在pandas中的数据帧上运行了一个相当复杂的过滤器(我正在过滤通过字典对67个不同的阈值传递测试结果)。为了做到这一点,我有以下内容:

query_string = ' | '.join([f'{k} > {v}' for k , v in dictionary.items()])
test_passes = df.query(query_string, engine='python')

其中k是测试名称,v是阈值。

这很好用,我可以将测试传递的行导出到csv。

我想知道是否还有一种方法可以附加一个计算测试通过次数的列。因此,例如,如果特定行记录1-67次测试通过。

python pandas
3个回答
1
投票

因此,我最终在解决了最初发布的pandas查询后开始使用以下内容进行“解决”。最初的问题是我的用例测试通过,如果实际上测试失败....

test_failures = data.query(query_string, engine='python').copy()

该副本是为了防止无意的数据操作和链接错误消息。

for k, row in test_failures.iterrows():
    failure_count=0
    test_count=0
    for key, val in threshold_dict.items():
        test_count +=1
        if row[key] > val:
            failure_count +=1
    test_failures.at[k, 'Test Count'] = test_count
    test_failures.at[k, 'Failure Count'] = failure_count

从我所读到的iterrows()不是最快的迭代方法,但它确实分别提供索引(k)和数据字典(行),我发现这些目的比在itertuples()中返回的元组更有用。

sorted_test_failures = test_failures.sort_values('Failure Count', ascending=False)  

sorted_test_failures.to_csv('failures.csv', encoding='utf8')

一点点整理和保存完成。

我已经测试了一个虚拟数据集(8000 x 66) - 它没有提供突破性的速度,但它完成了这项工作。任何改进都会很棒!


0
投票

这回答了这里:

https://stackoverflow.com/a/24516612/6815750

但举一个例子,你可以做到以下几点:

new_df = df.apply(pd.Series.value_counts, axis = 1) #where df is your current dataframe holding the pass/fails

df[new_df.columns] = new_df

Example


0
投票

您可以使用以下方法:

dictionary = {'a':'b', 'b': 'c'}
data = pd.DataFrame({'a': [1,2,3], 'b': [ 2,1,2], 'c': [2,1,1] })
test_components = pd.DataFrame([df.loc[:, k] > df.loc[:, v] for k , v in dictionary.items()]).T
# now can inspect what conditions were met in `test_components` variable
condition = test_components.any(axis=1)
data_filtered = data.loc[common_condition, :] 
© www.soinside.com 2019 - 2024. All rights reserved.