xirururu
xirururu

Reputation: 5508

How to get row position instead of row name in python pandas?

I have a dataframe with rowname, I want to select the rows after given conditions and then, I want to get the row position instead of the row name, how can I do that?

For example: I generated the myDf dataset, I want to select alle the items, which column A > 0, and return the position of the rows instead of the row name.

My desired output is: [0,1,2] instead of [1,2,2]

# Generate the dataset
np.random.seed(1)
rowname = [1,2,2,2,4,4]
myDf = pd.DataFrame(np.random.randn(6,4), index=rowname, columns=list('ABCD'))
print myDf
>>>
          A         B         C         D
 1  1.624345 -0.611756 -0.528172 -1.072969
 2  0.865408 -2.301539  1.744812 -0.761207
 2  0.319039 -0.249370  1.462108 -2.060141
 2 -0.322417 -0.384054  1.133769 -1.099891
 4 -0.172428 -0.877858  0.042214  0.582815
 4 -1.100619  1.144724  0.901591  0.502494

(If I use the code myDf[myDf.A>0].index, I will get [1,2,2], this is not I want.)

Upvotes: 0

Views: 324

Answers (1)

user2285236
user2285236

Reputation:

It's a little bit ugly but:

myDf.reset_index(drop=True)[myDf.reset_index()["A"]>0]
Out[93]: 
          A         B         C         D
0  1.624345 -0.611756 -0.528172 -1.072969
1  0.865408 -2.301539  1.744812 -0.761207
2  0.319039 -0.249370  1.462108 -2.060141

Upvotes: 2

Related Questions