2

Has the title say, I would like to find a way to drop the row (erase it) in a data frame from a column to the end of the data frame but I don't find any way to do so.

I would like to start with

A    B    C
-----------
1    1    1
1    1    1
1    1    1

and get

A    B    C
-----------
1        
1        
1       

I was trying with

df.drop(df.loc[:, 'B':].columns, axis = 1, inplace = True)

But this delete the column itself too

A
-
1        
1        
1       

am I missing something?

6
  • 3
    Check df.loc[:, df.columns != 'A'] = '' Commented Feb 16, 2021 at 17:12
  • 1
    There must be something in those cells, either a ' ', or np.nan, or any kind of character. Commented Feb 16, 2021 at 17:12
  • I would like to make the drop but I only know the name of the last column I need to keep the row Commented Feb 16, 2021 at 17:33
  • I would like to keep the first row event if the column is empty Commented Feb 16, 2021 at 17:36
  • It is not very clear what you're trying to achieve.. Commented Feb 16, 2021 at 17:46

1 Answer 1

3

If you only know the column name that you want to keep:

import pandas as pd

new_df = pd.DataFrame(df["A"])

If you only know the column names that you want to drop:

new_df = df.drop(["B", "C"], axis=1)

For your case, to keep the columns, but remove the content, one possible way is:

new_df = pd.DataFrame(df["A"], columns=df.columns)

Resulting df contains columns "A" and "B" but without values (NaN instead)

Sign up to request clarification or add additional context in comments.

2 Comments

When I do that, as I said, I drop the first line ( B C ) to, but I want to keep it
Ok, I edited the answer. This is in fact very special use case.

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.