Certainly! Here are six different ways to create new columns using Python pandas:
- Creating a new column using the
df.insert() method:
import pandas as pd
# create a new column called 'age' with values from another column
df = pd.read_csv('data.csv')
df['age'] = df['name'].apply(lambda x: int(x[0][0]) - int(x[1][0]))
print(df)
This code creates a new column called 'age' by applying a function to the values in another column. In this case, the function takes the values in the 'name' column, splits them into a tuple, and then subtracts the second element from the first element to get the age.
- Creating a new column using the
df.mask() method:
import pandas as pd
# create a new column called 'age' with missing values
df = pd.read_csv('data.csv')
# create a new column called 'age' with missing values
df['age'] = df['name'].mask(lambda x: 0 if x.isna().any() else x)
print(df)
This code creates a new column called 'age' by masking the values in another column based on whether they are missing or not. If a value is missing, the new column is set to 0.
- Creating a new column using the
df.apply() method:
import pandas as pd
# create a new column called 'age' with values from another column
df = pd.read_csv('data.csv')
# create a new column called 'age' with values from another column
df['age'] = df['name'].apply(lambda x: x.str.split(' ').iloc[0])
print(df)
This code creates a new column called 'age' by applying a function to the values in another column. In this case, the function takes the values in the 'name' column, splits them into a list, and then takes the first element of the list.
- Creating a new column using the
df.groupby() method:
import pandas as pd
# create a new column called 'age' based on a groupby operation