Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map a row index back to the original indexed dataframe

Tags:

python

pandas

Let us say I have a dataframe, and I want to find all negative values of a column, like this:

df_negAssets = df_original[df_original["assets"] < 0]

Now I have a new dataframe, out of my original indexed dataframe. This dataframe might contain 7 rows.

My question is: how do I map these 7 rows to the original dataframe?

df_negAssets.iloc(2) 

gives me the third row. But which row in my original dataframe does it corresponds to? Is it row 59? How can I find out that index "2" in my view, corresponds to index "59" in my original dataframe? And how do I go back? "2" -> "59", and how to find out that "59" -> "2"?

like image 660
Orvar Korvar Avatar asked Dec 10 '25 19:12

Orvar Korvar


1 Answers

To get the mapping:

df_negAssets.index

> How can I find out that index "2" in the new dataframe, corresponds to index "59" in my original dataframe?

df_negAssets.index[2] == 59

> And how do I go back? ... and how to find out that "59" -> "2"?

numpy.where(df_negAssets.index == 59)[0][0] == 2

Are you sure you need to? Remember you can use df_negAssets[59].

By the way, df_negAssets is not a view. It's a new DataFrame. If you take an entire column, or a slice (df[0][x:y:z]) then it can be a view. When you use a condition like <0, it creates a new DataFrame.

like image 70
cyborg Avatar answered Dec 12 '25 12:12

cyborg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!