I would like to easily split my column into two (or more) using apply. (I could use split like they do here, but there are exceptions that would difficult to handle. This answer is similar, but again outputs one column.
import pandas as pd
df = pd.DataFrame({"xVal":[1,2,7,4], "xRef":["1-2","2-3",">4", "NoReference"]})
def sep_ref(row):
if '-' in row:
return row.split("-")
else:
# handle and return some list
return [row, row]
# broken assinment
df['xlow'], df['xhigh'] = df.xRef.apply(sep_ref)
df
xVal xRef
0 1 '1-2'
1 2 '2-3'
2 7 '>4'
3 4 'NoReference'
desired output
xVal xlow xhigh
0 1 1 2
1 2 2 3
2 7 4 NaN
3 4 NaN NaN
The easy solution is to run two separate apply functions, but this is less elegant and could make exception handling more difficult. Is there a way to append 2 columns at once with apply?