Add column to DataFrame columns - ( Pandas Operations )
Heading h2
Syntax
DataFrame['new_column'] = value
Example
import pandas as pd
df = pd.DataFrame({'name': ['John', 'Mike', 'Sarah'], 'age': [34, 29, 41], 'gender': ['M', 'M', 'F']})
df['salary'] = [65000, 75000, 80000]
print(df)
Output
name age gender salary
0 John 34 M 65000
1 Mike 29 M 75000
2 Sarah 41 F 80000
Explanation
Adding a column to a Pandas DataFrame is a common operation in data analysis and manipulation. To add a new column, we select the DataFrame object and then assign the new column a name and a value.
In the above example, we create a DataFrame with columns name
, age
, and gender
. We then add a new column salary
to the DataFrame with values [65000, 75000, 80000]
. This is accomplished by selecting the DataFrame object df
and assigning the new column a name and a list of the new values to be added.
Use
Adding a new column to a Pandas DataFrame is a simple and convenient way to expand the data with additional information or computations. The new column is automatically aligned with the existing data and can be used in further analysis or visualization.
Important Points
Adding a column to a Pandas DataFrame requires selecting the DataFrame object and assigning a new column a name and a value.
The value can be a constant value or a list of values.
The new column is automatically aligned with the existing data and can be used in further analysis or visualization.
Adding a new column is a non-destructive operation, which means that the original DataFrame is not modified.
Summary
In conclusion, Pandas provides a simple and convenient method for adding a new column to an existing DataFrame object. The operation is non-destructive and can be easily reversed if needed. Adding a new column is a common data manipulation operation in data analysis and can be useful for expanding the data with additional information or computations.