pythonpandas

How to extract City From Purchase Address Column using Python


I want to create a new column in df called a city

This is how the column looks like in df data frame:

   **Purchase Address**
   917 1st St, Dallas, TX 75001
   682 Chestnut St, Boston, MA 0221

My Expected output should be a new column in df called a city where values between the comma (,) should be in place for example......

   **City**
   Dallas
   Boston

Solution

  • below code will work if you don't have any NA values in the address column and the format of address is fixed.

    df['city']=[x.split(',')[1] for x in df['Purchase Address'].values]