Search code examples
pythonpandasdataframedata-analysis

Using pandas DataFrame.apply for column operations


So I have a pandas DataFrame that looks like:

       Compression Velocity  Compression Force  
1         -8.373589E-03           6.810879
2            -0.9864202           140.6932 
3              -1.97424           158.4015
4             -2.984882           171.0502
5             -3.976808           178.6395
6             -4.987449           186.2288
7             -5.941944           191.2883
8             -6.952637           198.8775
9             -7.963353            203.937
10            -8.955353           208.9965
11            -9.947352            214.056 

The first column, 'Compression Velocity', is recorded in inches/second and the second column, 'Compression Force', is in force-lbs. I want to convert the first column into meters/second and the second column into newtons. After reading through the pandas DataFrame documentation I believe that I can do column wise operations using the DataFrame.apply() function as described here.

However I am struggling to figure out how to apply one function convertToMeters to the first column and convertToNewtons for the second column.

If I try:

dataframe.apply(convertToMeters, axis=0)

or

dataframe.apply(converToNewtons, axis=0)

it will apply the respective function to each column and not just the desired column.

Is there a way to designate which column I want each function to be applied to?


Solution

  • For simple arithmetic like unit conversion, This will do it:

     dataframe['Compression Velocity'] *= 0.0254