Slice / split Pandas Dataframe

Viewed 56

How do take a dataframe with 10 columns labelled Apple, Bee, Charlie, Dino, Echo, Free, Guitar, Hello, Ignite, June and create a new data from it with a select few of the column - for example a dataframe with 2 of the columns Apple and Echo and then another dataframe with 3 of the columns Guitar, Hello and Bee.

2 Answers
df1 = df[['Apple', 'Bee']]
df2 = df[['Guitar', 'Hello', 'Bee']]

The easiest way to slice multiple columns from any dataframe is shown here. This method extends from the usual way of querying a single column from a dataframe using df['column_name']. Here, instead of passing a string, we pass an entire list of strings representing different columns to query-> df[['col1', 'col2', 'col3']]

So you learn how to run iloc, then pandas concat. These will help you I guess. Since the sample of the question isn't clear, I suggest you look here.

If this help you, try it:

import pandas as pd
df = pd.DataFrame(columns=("A","B","C","D"))
df2 = df.iloc[:,:2]

It will show the only first 2 column.

Related