using split()¶
In [1]:
import pandas as pd
data = {
''''full_address'''': [
''''123 Main St, Springfield, IL, 62701'''',
''''456 Elm St, Shelbyville, IL, 62565'''',
''''789 Oak St, Capital City, IL, 62702''''
]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df[[''''street'''', ''''city'''', ''''state'''', ''''zip_code'''']] = df[''''full_address''''].str.split('''', '''', expand=True)
print("\nUpdated DataFrame:")
print(df)
df.drop(columns=[''''full_address''''], inplace=True)
print("\nFinal DataFrame:")
print(df)
Original DataFrame: full_address 0 123 Main St, Springfield, IL, 62701 1 456 Elm St, Shelbyville, IL, 62565 2 789 Oak St, Capital City, IL, 62702 Updated DataFrame: full_address street city state 0 123 Main St, Springfield, IL, 62701 123 Main St Springfield IL 1 456 Elm St, Shelbyville, IL, 62565 456 Elm St Shelbyville IL 2 789 Oak St, Capital City, IL, 62702 789 Oak St Capital City IL zip_code 0 62701 1 62565 2 62702 Final DataFrame: street city state zip_code 0 123 Main St Springfield IL 62701 1 456 Elm St Shelbyville IL 62565 2 789 Oak St Capital City IL 62702
using regular expressions¶
In [2]:
import pandas as pd
data = {
''''full_address'''': [
''''123 Main St, Springfield, IL, 62701'''',
''''456 Elm St, Shelbyville, IL, 62565'''',
''''789 Oak St, Capital City, IL, 62702''''
]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df[[''''street'''', ''''city'''', ''''state'''', ''''zip_code'''']] = df[''''full_address''''].str.extract(r''''^(.*),\s(.*),\s([A-Z]{2}),\s(\d{5})$'''')
print("\nUpdated DataFrame:")
print(df)
df.drop(columns=[''''full_address''''], inplace=True)
print("\nFinal DataFrame:")
print(df)
Original DataFrame: full_address 0 123 Main St, Springfield, IL, 62701 1 456 Elm St, Shelbyville, IL, 62565 2 789 Oak St, Capital City, IL, 62702 Updated DataFrame: full_address street city state 0 123 Main St, Springfield, IL, 62701 123 Main St Springfield IL 1 456 Elm St, Shelbyville, IL, 62565 456 Elm St Shelbyville IL 2 789 Oak St, Capital City, IL, 62702 789 Oak St Capital City IL zip_code 0 62701 1 62565 2 62702 Final DataFrame: street city state zip_code 0 123 Main St Springfield IL 62701 1 456 Elm St Shelbyville IL 62565 2 789 Oak St Capital City IL 62702