Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To send the result of a function back to a DataFrame, you can use the assignment operator (=) to assign the function's output to a new column in the DataFrame.

For example:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Define a function
def multiply_columns(row):
    return row['A'] * row['B']

# Apply the function and assign the result to a new column
df['C'] = df.apply(multiply_columns, axis=1)

print(df)

This code defines a function called multiply_columns, which takes a row of the DataFrame as input and multiplies the values in columns 'A' and 'B'. Then, the function is applied to each row of the DataFrame using the apply method and the result is assigned to a new column 'C' using the assignment operator (=). Finally, the DataFrame is printed to show the new column 'C' with the result of the function.