2

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

1 Answer 1

1

You can do with drop

df1=df.iloc[:,col_index].copy()
df2=df.drop(df1.columns.tolist(),axis=1).copy()
Sign up to request clarification or add additional context in comments.

2 Comments

depending on what you are doing with those df you might want to return df1 and df2 as copies, so you don't accidentally edit the main df, of which df1 and df2 are slices.
@Wen-Ben there is a small typo in the 1st line. If you correct that I will mark it as an answer. df1=df.iloc[:,col_index].copy()

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.