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

12,561

Solution 1

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)

Solution 2

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')]

Share:
12,561
Ash
Author by

Ash

Updated on June 04, 2022

Comments

  • Ash
    Ash almost 2 years

    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.