Articles → PANDAS → Add And Delete Columns From Dataframe In Pandas

Add And Delete Columns From Dataframe In Pandas






Adding A New Column




import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(5,4),['A', 'B', 'C', 'D', 'E'],['W', 'X', 'Y', 'Z'])

print("DataFrame before adding a new column\n")
print(df)

# Adding a new column
df['New Column'] = df['W'] + df['X']

print("\nDataFrame after adding a new column\n")
print(df)




Picture showing the output when a new column is added in dataframe in pandas
Click to Enlarge




Deleting A Column




import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(5,4),['A', 'B', 'C', 'D', 'E'],['W', 'X', 'Y', 'Z'])



print("\nDataFrame before deleting new column\n")
print(df)

df = df.drop('X', axis=1)

print("\nDataFrame after deleting new column\n")
print(df)




Picture showing the dataframe in pandas after the column is deleted
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Friday, April 12, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250