Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to apply the transform() function to multiple columns in pandas without a for loop is to use the apply() method along with a lambda function. Here's an example:

Suppose we have a DataFrame with three columns: 'col1', 'col2', and 'col3':

import pandas as pd

df = pd.DataFrame({
    'col1': [1, 2, 3],
    'col2': [4, 5, 6],
    'col3': [7, 8, 9]
})

We want to apply a transformation function (e.g. the square root function) to all three columns. We can do this using the following code:

df[['col1', 'col2', 'col3']] = df[['col1', 'col2', 'col3']].apply(lambda x: x.transform(np.sqrt))

Here, we first select the three columns we want to transform using the double square bracket notation [['col1', 'col2', 'col3']]. We then apply the lambda function lambda x: x.transform(np.sqrt) to these columns using the apply() method. The lambda function applies the transform() function with the square root function (np.sqrt) to each column x in the DataFrame.

After running this code, the DataFrame df will have the transformed values in the 'col1', 'col2', and 'col3' columns.