MERGING AND SPLITTING COLUMNS IN PANDAS
Listing B.20 shows the contents of employees.csv and Listing B.21 shows the contents of emp_merge_split.py; these examples illustrate how to merge columns and split columns of a CSV file.
Listing B.20: employees.csv
name,year,month Jane-Smith,2015,Aug Dave-Smith,2020,Jan Jane-Jones,2018,Dec Jane-Stone,2017,Feb Dave-Stone,2014,Apr Mark-Aster,,Oct Jane-Jones,NaN,Jun
Listing B.21: emp_merge_split.py
import pandas as pd
emps = pd.read_csv("employees.csv")
print("emps:")
print(emps)
print()
emps['year'] = emps['year'].astype(str)
emps['month'] = emps['month'].astype(str)
# separate column for first name and for last name:
emps['fname'],emps['lname'] = emps['name'].str.
split("-",1).str
# concatenate year and month with a "#" symbol:
emps['hdate1'] = emps['year'].
astype(str)+"#"+emps['month'].astype...