Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to append a column to DataFrame in pandas

Sarvech Qadir

Suppose you want to create a pandas DataFrame using the Python pandas library. To do so you will first initialize the data:

import pandas as pd 

data = {'Name': ['Mike', 'Alex', 'George'], 
        'Age': [23, 22, 25}

df = pd.DataFrame(data) 

Then, you will use the code above create the table below:

The DataFrame df

Now, suppose you want to append another column to this DataFrame called City. To do so, write:

city = ['London', 'New York', 'Madrid'] 
  
df['City'] = city   
The updated DataFrame df
import pandas as pd 

data = {'Name': ['Mike', 'Alex', 'George'], 
        'Age': [23, 22, 25]}
print("print data", data)

df = pd.DataFrame(data)

print("printing dataframe")
print(df)

city = ['London', 'New York', 'Madrid'] 
  
df['City'] = city   
print("printing dataframe after appending a column")
print(df)

RELATED TAGS

python

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring