0

I need to drop some lines from dataframe with python , based on multiple values

Code Names Country
1      a    France
2      b    France
3      c    USA
4      d    Canada
5      e    TOTO
6      f    TITI
7      g    Corona

I need to have this

Code Names Country
1      a    France
4      d    Canada
5      e    TOTO
7      g    Corona

I do this :

df.drop(df[('f','b','c')in df['names']].index)

But it doesnt work : KeyError: False

it works for only one key like this : df.drop(df['f' in df['names']].index)

Do you have any idea ?

3
  • 2
    Just , isin and inverseoutput = df[~df['Names'].isin(['f','b','c'])].copy() ? I dont hink you need the drop here , boolean indexing is enough Commented May 13, 2020 at 19:07
  • @ankyy "isin() takes 2 positional arguments but 3 were given " Commented May 13, 2020 at 19:13
  • Can you post the isin code you are trying. Looks like something is off Commented May 14, 2020 at 3:14

3 Answers 3

1

To remove rows of certain values:

indexNames = df[df['Names'].isin(['f', 'b', 'c'])].index
df.drop(indexNames, inplace=True)
print(df)

Output:

   Code Names Country
0     1     a  France
3     4     d  Canada
4     5     e    TOTO
6     7     g  Corona
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but they are not really the same, so duplicated won't work :(
Did this work? If yes, Mark this as the answer and close it.
1

Based on your example, I think this may be what you are looking for.

new_df = df.loc[~df.Names.isin(['f','b','c'])].copy()
new_df

Output:

    Code    Names   Country
0   1       a       France
3   4       d       Canada
4   5       e       TOTO
6   7       g       Corona

Comments

1

In pandas, we can use .drop() function to drop column and rows.

For dropping specific rows, we need to use axis = 0

So your required output can be achieved by following line of code :

df4.drop([1,2,5], axis=0)

The output will be :

code    Names   Country
1        a      France
4        d      Canada
5        e      TOTO
7        g      Corona

1 Comment

I can't use isnin i have this error : isin() takes 2 positional arguments but 4 were give , Any other suggestions ?

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.