Skip to content
Advertisement

how to divide a column element wise in python

I want to divide the first column of this table element wise by 3.6.

dict_read = {
'tractionForceTable': [']traction_V(km/h)_Force(N)', 'table']}

outputdict = {key: framehandle.value_readin(value) for (key, value) in dict_read.items()}`

enter image description here

It throws an error something like :

 outputdict["traction_ForceTable"] = outputdict["tractionForceTable"][:, 0] / 3.6
  File "C:UsershppatDesktopvenvlibsite-packagespandascoreframe.py", line 3505, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:UsershppatDesktopvenvlibsite-packagespandascoreindexesbase.py", line 3636, in get_loc
    self._check_indexing_error(key)
  File "C:UsershppatDesktopvenvlibsite-packagespandascoreindexesbase.py", line 5651, in _check_indexing_error
    raise InvalidIndexError(key)
pandas.errors.InvalidIndexError: (slice(None, None, None), 0)

Here’s what I tried:

outputdict["traction_Table"] = outputdict["tractionForceTable"][:, 1] / 3.6

Advertisement

Answer

There are several ways to do it, here are two. I suggest from your error message that your data is in a pd.DataFrame. I used a shortened version of your data.

import pandas as pd 
df = pd.DataFrame({'velocity': [1,2,3,4,5],
                   'mfbp': [36600000, 1800000, 1200000, 900000, 720000]})
   

You could use map (or apply) and define a lambda function that is applied to every cell.

df['mfbp'].map(lambda x: x/3.6)

Or you use the pandas built-in method pd.Series.divide

df['mfbp'].divide(3.6)

Output in both cases:

0    1.016667e+07
1    5.000000e+05
2    3.333333e+05
3    2.500000e+05
4    2.000000e+05
Advertisement