In [1]:
# Deep Copy
# Changes to the new DataFrame will not affect the original DataFrame
import pandas as pd
df = pd.DataFrame({
''''''''A'''''''': [1, 2, 3],
''''''''B'''''''': [''''''''x'''''''', ''''''''y'''''''', ''''''''z'''''''']
})
df_copy = df.copy()
print(df_copy)
A B 0 1 x 1 2 y 2 3 z
In [2]:
# Shallow Copy
# Changes to the data in the new DataFrame will affect the original DataFrame and vice versa
import pandas as pd
df = pd.DataFrame({
''''''''A'''''''': [1, 2, 3],
''''''''B'''''''': [''''''''x'''''''', ''''''''y'''''''', ''''''''z'''''''']
})
df_shallow_copy = df.copy(deep=False)
print(df_shallow_copy)
A B 0 1 x 1 2 y 2 3 z
In [3]:
# Copying a Subset of a DataFrame
import pandas as pd
df = pd.DataFrame({
''''''''A'''''''': [1, 2, 3],
''''''''B'''''''': [''''''''x'''''''', ''''''''y'''''''', ''''''''z''''''''],
''''''''C'''''''': [True, False, True]
})
df_subset_copy = df[df[''''''''C'''''''']].copy()
print(df_subset_copy)
A B C 0 1 x True 2 3 z True
In [4]:
# Copying Rows Based on a Condition
import pandas as pd
df = pd.DataFrame({
''''''''A'''''''': [1, 2, 3, 4],
''''''''B'''''''': [''''''''x'''''''', ''''''''y'''''''', ''''''''z'''''''', ''''''''w''''''''],
''''''''C'''''''': [True, False, True, False]
})
df_subset_copy = df[df[''''''''A''''''''] > 1].copy()
print(df_subset_copy)
A B C 1 2 y False 2 3 z True 3 4 w False
In [5]:
# Copying Rows Based on Multiple Conditions
import pandas as pd
df = pd.DataFrame({
''''''''A'''''''': [1, 2, 3, 4],
''''''''B'''''''': [''''''''x'''''''', ''''''''y'''''''', ''''''''z'''''''', ''''''''w''''''''],
''''''''C'''''''': [True, False, True, False]
})
df_subset_copy = df[(df[''''''''A''''''''] > 1) & (df[''''''''C''''''''] == True)].copy()
print(df_subset_copy)
A B C 2 3 z True