1

I have dataframe(ratings_base) which contains 100000 rows. I am filtering one row from it and I used following code segment for it.

((ratings_base.loc[ratings_base['user_id'] == 1]).sort_values(by='rating', ascending=0)).iloc[0]

which returns me a Series object.

user_id       1
movie_id    170
rating        5
Name: 19996, dtype: int64

How can I delete this row(Series object) from my original dataframe object ? I can use dataframe's drop function but I need row index for it. If I can get the row index of the selected row (I can see it appears as the Name attribute of the Series object), I can drop it.

Malintha
  • 4,512
  • 9
  • 48
  • 82

1 Answers1

1

df.loc[0] selects the first row. df.loc[1:] selects everything after the first row.

So you could use

ratings_base = ((ratings_base.loc[ratings_base['user_id'] == 1])
                .sort_values(by='rating', ascending=0))
ratings_base = ratings_base.iloc[1:]

Alternatively, you could use df.drop:

row = ((ratings_base.loc[ratings_base['user_id'] == 1])
       .sort_values(by='rating', ascending=0)).iloc[0]
label = row.name
ratings_base = ratings_base.drop(label)

This may be more flexible if you wish to drop a row which does not happen to be the first.

Note that ratings_base.drop will drop all rows whose index is label. So more than one row may be dropped if the index is not unique.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Prefer the alternative and also it worked me. Have side question. I had to use "inplace=True" property to get it dropped. I checked len(rating_base) to confirm whether it is dropped. Without "inplace=True" property I saw length was 100000 and with that prop it was 99999. What is the reason? – Malintha Oct 22 '16 at 13:20
  • 1
    When you call `df.drop(..., inplace=True)`, `drop` modifieds `df` and returns `None`. When you call `df.drop(...)`, `df` is not modified and `drop` returns a new DataFrame. So to change the value of `df` you would need to use an assignment: `df = df.drop(...)`. I prefer the latter (avoiding `inplace=True`) because the name `inplace` is misleading -- it is not a truly inplace operation in the sense that it does not save temporary memory. See also http://stackoverflow.com/a/22533110/190597 for other reasons to avoid `inplace`. – unutbu Oct 22 '16 at 13:49