Ash
Ash

Reputation: 73

Pandas - how do you create a new data frame based on another dataframe?

I have a dataframe that contains school types and their locations. One of the columns is "Institude_Type" and the two school types are "Secondary (non-grammar) School" and "Secondary (grammar) School". I want to take all of the Secondary (non-grammar) School's information and put it into another dataframe - but I'm not sure how to do this.

I want it to be an exact copy of the current DF, with all the same 8 columns. Just one with the grammar and the other with non grammar schools.

Thanks in advance.

Upvotes: 2

Views: 17273

Answers (2)

mcbridecaleb
mcbridecaleb

Reputation: 101

This previous Stack Overflow answer should help:

create a new dataframe from selecting specific rows from existing dataframe python

This process requires a Boolean operator, such that it only applies to a portion of the dataframe where the condition is true. This requires () within the [].

Code:
df2 = df[(df['Institude_Type'] == 'Secondary (non-grammar) School')]
df3 = df[(df['Institude_Type'] == 'Secondary (grammar) School')]

Upvotes: 1

Omar
Omar

Reputation: 329

use the built-in copy function:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html

For example:

schoolCopy = schoolDataFrame[allTheColumnsRequired].copy(deep=True)

Upvotes: 2

Related Questions