Create a new dataframe from existing dataframe pandas

You can create a new DataFrame from an existing DataFrame in pandas using various methods. Here are a few examples:

Method 1: Using the copy() method

import pandas as pd

# create an existing DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# create a new DataFrame by copying the existing one
new_df = df.copy()

print(new_df)

This will create a new DataFrame new_df that is a copy of the original DataFrame df.

Method 2: Using the assign() method

import pandas as pd

# create an existing DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# create a new DataFrame by assigning a new column to the existing one
new_df = df.assign(C=[7, 8, 9])

print(new_df)

This will create a new DataFrame new_df that is a copy of the original DataFrame df with an additional column C.

Method 3: Using the loc[] method

import pandas as pd

# create an existing DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# create a new DataFrame by selecting a subset of rows and columns from the existing one
new_df = df.loc[:, ['A', 'B']]

print(new_df)

This will create a new DataFrame new_df that is a subset of the original DataFrame df, containing only the columns A and B.

Method 4: Using the concat() method

import pandas as pd

# create an existing DataFrame
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'C': [7, 8, 9], 'D': [10, 11, 12]})

# create a new DataFrame by concatenating two DataFrames
new_df = pd.concat([df1, df2])

print(new_df)

This will create a new DataFrame new_df that is the concatenation of two DataFrames df1 and df2.

These are just a few examples of how you can create a new DataFrame from an existing one in pandas. The method you choose will depend on your specific use case and requirements.