In [1]:
# Adding a Column with a Constant Value
import pandas as pd
df = pd.DataFrame({
''''A'''': [1, 2, 3],
''''B'''': [4, 5, 6]
})
df[''''C''''] = 7
print(df)
A B C 0 1 4 7 1 2 5 7 2 3 6 7
In [2]:
# Adding a Column with a List of Values
import pandas as pd
df = pd.DataFrame({
''''A'''': [1, 2, 3],
''''B'''': [4, 5, 6]
})
df[''''C''''] = [7, 8, 9]
print(df)
A B C 0 1 4 7 1 2 5 8 2 3 6 9
In [3]:
# Adding a Column Based on Another Column
import pandas as pd
df = pd.DataFrame({
''''A'''': [1, 2, 3],
''''B'''': [4, 5, 6]
})
df[''''C''''] = df[''''A''''] + df[''''B'''']
print(df)
A B C 0 1 4 5 1 2 5 7 2 3 6 9
In [4]:
# Using assign() Method
import pandas as pd
df = pd.DataFrame({
''''A'''': [1, 2, 3],
''''B'''': [4, 5, 6]
})
df = df.assign(C=[7, 8, 9], D=[10, 11, 12])
print(df)
A B C D 0 1 4 7 10 1 2 5 8 11 2 3 6 9 12