Use pandas

Use Python pandas to add default value to a .csv

Use Python pandas to add default value to a .csv

Let's look at how simple it can be to add a new column of some default information to a .csv file using Python pandas.

Suppose you have this set of data and you want to add a column to specify whether or not the home has been inspected by a home inspector. So far, none of the houses have been inspected, so we want to set all the column values to false.

We'll need to add a new column called Inspected and set the value to 'false' for each one.

homes_sorted.csv

AddressPriceBedrooms
992 Settled St823,0494
1506 Guido St784,0493
247 Fort St299,2383
132 Walrus Ave299,0012
491 Python St293,9234
4981 Anytown Rd199,0004
938 Zeal Rd148,3982
123 Main St99,0001

How to add a new column with Python pandas

import pandas as pd
df_homes = pd.read_csv("C:/Users/kennethcassel/homes_sorted.csv")
# To make a new column with values that are all the same,
# do the following. Name the column, and assign it to a single
# default value. This will populate every row with that value.
df_homes['Inspected'] = 'false'
df_homes.to_csv('homes_inspected.csv', index=False)

Resulting file with new column added

homes_inspected.csv

AddressPriceBedroomsInspected
992 Settled St823,0494false
1506 Guido St784,0493false
247 Fort St299,2383false
132 Walrus Ave299,0012false
491 Python St293,9234false
4981 Anytown Rd199,0004false
938 Zeal Rd148,3982false
123 Main St99,0001false
Edit this page on GitHub