Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...