简体   繁体   中英

split and merge pandas dataframe based on input column index

I have a pandas dataframe test_df . This dataframe contains 20 columns. I am given a list of column index col_index = [3, 5] for example.

I need to create two separate dataframes

  • one only including the columns in col_index
  • other includes all the columns except the columns in col_index

How do I do that?

I understand I can do

new_df = df.iloc[:, 3] 

To create a dataframe out of column number 3. But what do I do as in this case I have multiple column numbers to separate out from the main dataframe?

Using python 3

You can do with drop

df1=df.iloc[:,col_index].copy()
df2=df.drop(df1.columns.tolist(),axis=1).copy()

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