Get index of row within a sub-DataFrame with pandas apply

Viewed 150

This question is related to but different from this one, which wonders how to access the row index from within apply. That can be done with row.name. However, in my case I am applying a function to query'd dataframe, and the row's name are just their index in the original df. I need them to be zero-based for the queried DataFrame.

import pandas as pd


def print_name(r):
    print(r.name)

data = {"seg": [1, 1, 1, 2, 2, 2], "text": ["i", "like", "you", "do", "you", "see"]}
df = pd.DataFrame(data=data)
sub = df.query("seg==2")
sub.apply(print_name, axis=1)
# 3
# 4
# 5
# Expected 0, 1, 2
1 Answers

I think you want default index, because filtered rows has original index, there is no change:

sub = df.query("seg==2").reset_index(drop=True)

print (df.query("seg==2"))
   seg text
3    2   do
4    2  you
5    2  see

print (df.query("seg==2").reset_index(drop=True))
   seg text
0    2   do
1    2  you
2    2  see
Related