I am trying to use apply function to assign new values to two existing columns in a dataframe slice using a .loc query.
To reproduce - first create a dataframe:
import re
import panads as pd
data = [[1000, "MSL", "Test string"], [2000, 'AGL', 'other string'], [0, 'AGL', "xxxx SFC-10000ft MSLXXX"]]
df = pd.DataFrame(data=data, columns=['Alt', "AltType",'FreeText'])
Then create the apply function
def testapply(row):
try:
match = re.findall("SFC-([0-9]+)FT (MSL|AGL|FL)", row.FreeText)[0]
return (int(match[0]), match[1])
except:
return (0, row.AltType)
When I run
df.loc[df['Alt']==0, ['Alt', 'AltType']] = df.loc[df['Alt']==0].apply(testapply, axis=1)
I would like to get as a result is:
Alt AltType FreeText
0 1000 MSL Test string
1 2000 AGL other string
2 10000 MSL xxxx SFC-10000ft MSLXXX
but what I end up getting is:
Alt AltType FreeText
0 1000 MSL Test string
1 2000 AGL other string
2 (10000, MSL) (10000, MSL) xxxx SFC-10000FT MSLXXX
Does anyone know how to make this work in one fell swoop?