0

I've created a loop to get a list of rows to drop.

cols = []
for i in range(len(df)):
    if i != len(df)-1:
        if (df['Player'][i] == df['Player'][i+1]):
            cols.append(i+1)

Now I want to go through cols and drop each row by its number. I've tried using the following loop to drop these rows but it's not working.

for col in cols:
    df.drop([[col]])
1
  • By default, df.drop() returns a dataframe, rather than modifying it in place; supplying an inplace = True argument should make your code work the way you want it to. But there is a better way to do this; see my answer below. Commented Mar 28, 2017 at 4:44

3 Answers 3

1

For dropping rows:

df.drop(rows,inplace=True)

For dropping columns:

df.drop(cols,axis=1,inplace=True)

Test:

df = pd.DataFrame({'A':[1,2,3,4,5],'B':[1,2,3,4,5]})
print('DataFrame with initialised :\n',df,'\n')
df.drop([2,4],inplace=True)
print('DataFrame after dropping 2 rows:\n',df,'\n')
df.drop(['B'],axis=1,inplace=True)
print('DataFrame after dropping 1 column:\n',df,'\n')

Output:

DataFrame with initialised :
   A  B
0  1  1
1  2  2
2  3  3
3  4  4
4  5  5 

DataFrame after dropping 2 rows:
   A  B
0  1  1
1  2  2
3  4  4 

DataFrame after dropping 1 column:
   A
0  1
1  2
3  4 
Sign up to request clarification or add additional context in comments.

Comments

0

if you just want to delete rows with duplicated value in col 'Player', you can:

df.drop_duplicates(subset=['Player'],inplace=True)

2 Comments

Seems like OP wants to drop dups only! Good call.
This is probably not the case though; it looks like OP only wants to drop rows immediately preceded by a duplicate value of Player.
0

It looks like you are trying to get rid of rows preceded by a duplicate value of Player. With pandas, always try to work with vectorization: df.Player == df.Player.shift() checks whether each entry in Player is equal to the last, so a one-line solution is

df[df.Player != df.Player.shift()]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.