I'm looking to apply a function to all but one column in pandas, whilst maintaining that column as it is originally. I have a working version that does what I need, but it seems unusually long for something so simple. I'm wondering if there is a better approach...
df = pd.DataFrame(columns = ['firstcol','secondcol','thirdcol'],
data=[['a1',1,'a6.1'],['b2',3,'b9.3'],['c12',4,'c2']])
My dataframe is made up of strings and integers. Each column is exclusive of a particular type, and I am looking to standardize so that all columns are numerical (integers or floats as I have some decimal values). So, in the toy data above, I need to transform the first and third columns, and leave the second column alone...
df.loc[:, df.columns != 'secondcol'] = df.loc[:, df.columns != 'secondcol'].applymap(lambda x: float(re.sub(r'[^\d.]','', x)))
For clarity, this line: (1) specifies all but the column named "secondcol", (2) uses the applymap and lambda functions to remove non-numeric (or decimal) characters, and (3) converts to a float.
This produces the desired output, but as I say isn't overly readable. Have I stumbled across the best way to do this, or is there a simpler alternative?