# Groupby on pre-filtered values

**URL:** <https://discuss.elastic.co/t/groupby-on-pre-filtered-values/354961>\
**Category:** Kibana\
**Created:** [March 7, 2024, 1:48pm UTC](https://discuss.elastic.co/t/groupby-on-pre-filtered-values/354961 "2024-03-07T13:48:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kassof](https://avatars.discourse-cdn.com/v4/letter/k/8e8cbc/32.png) [@kassof](https://discuss.elastic.co/u/kassof)\
**Post date:** [March 7, 2024, 1:48pm UTC](https://discuss.elastic.co/t/groupby-on-pre-filtered-values/354961/1 "2024-03-07T13:48:52Z")

</div>

Hello,

I aim to create a visualization in Kibana that mirrors the output obtained with the following Python pandas code. Please note that while the example code is in Python, my data resides within an Elasticsearch index.

```auto
import pandas as pd

# Assuming your dataframe is named df
data = {
    'a': [1, 1, 2, 2],
    'b': ['positive', 'negative', 'negative', 'negative'],
    'c': [5, 3, 3, 2]
}

df = pd.DataFrame(data)

# Filter rows where b is positive
positive_a = df[df['b'] == 'positive']['a']

# Filter rows where a is in positive_a
result = df[df['a'].isin(positive_a)].groupby('a')['c'].sum().reset_index()

print(result)

```

---

<div class="post-metadata">

**Author:** ![tsullivan](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tsullivan/32/31077_2.png) [@tsullivan](https://discuss.elastic.co/u/tsullivan)\
**Post date:** [March 19, 2024, 6:06pm UTC](https://discuss.elastic.co/t/groupby-on-pre-filtered-values/354961/2 "2024-03-19T18:06:21Z")

</div>

As long as all of these fields needed for this logic exist in a single document, you can use the Painless language to create runtime fields in the data, which act as plain fields you can use to filter the data.

See:

- [Use Painless scripts in runtime fields | Painless Scripting Language [8.12] | Elastic](https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-runtime-fields.html)
- [Runtime fields context | Painless Scripting Language [8.12] | Elastic](https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-runtime-fields-context.html)

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [April 16, 2024, 6:06pm UTC](https://discuss.elastic.co/t/groupby-on-pre-filtered-values/354961/3 "2024-04-16T18:06:54Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
