简体   繁体   中英

Panda drop values in columns but keep columns

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM