Get New pandas DataFrame from Existing Data in Python (2 Examples)
On this page you’ll learn how to create a new pandas DataFrame based on an existing DataFrame in Python programming.
Example Data
import pandas as pd # Import pandas |
import pandas as pd # Import pandas
df = pd.DataFrame({'A':range(1, 7), # Construct example pandas DataFrame 'B':['a', 'x', 'c', 'x', 'e', 'x'], 'C':[5, 9, 7, 8, 1, 1]}) print(df) # A B C # 0 1 a 5 # 1 2 x 9 # 2 3 c 7 # 3 4 x 8 # 4 5 e 1 # 5 6 x 1 |
df = pd.DataFrame({'A':range(1, 7), # Construct example pandas DataFrame 'B':['a', 'x', 'c', 'x', 'e', 'x'], 'C':[5, 9, 7, 8, 1, 1]}) print(df) # A B C # 0 1 a 5 # 1 2 x 9 # 2 3 c 7 # 3 4 x 8 # 4 5 e 1 # 5 6 x 1
Example 1: Duplicating Entire pandas DataFrame in Python
df_A = df.copy() # Create duplicate of pandas Data Frame print(df_A) # Print copy # A B C # 0 1 a 5 # 1 2 x 9 # 2 3 c 7 # 3 4 x 8 # 4 5 e 1 # 5 6 x 1 |
df_A = df.copy() # Create duplicate of pandas Data Frame print(df_A) # Print copy # A B C # 0 1 a 5 # 1 2 x 9 # 2 3 c 7 # 3 4 x 8 # 4 5 e 1 # 5 6 x 1
Example 2: Extracting Specific Variables of pandas DataFrame in Python
df_B = df[['A', 'C']].copy() # Get certain columns print(df_B) # A C # 0 1 5 # 1 2 9 # 2 3 7 # 3 4 8 # 4 5 1 # 5 6 1 |
df_B = df[['A', 'C']].copy() # Get certain columns print(df_B) # A C # 0 1 5 # 1 2 9 # 2 3 7 # 3 4 8 # 4 5 1 # 5 6 1
Further Resources & Related Articles
In addition, you might have a look at some of the other articles on statisticsglobe.com. You can find a selection of tutorials below.
- Concatenate pandas DataFrame to Existing CSV File in Python
- Create Dictionary from pandas DataFrame in Python
- Insert New Row at Arbitrary Position of pandas DataFrame in Python
- Add New Variable at Particular Location of pandas DataFrame in Python
- Adding a New Empty Column to a pandas DataFrame in Python