create a new column in pandas dataframe by applying a function to two columns for every…
- User
create a new column in pandas dataframe by applying a function to two columns for every row
Assistant
Here is how you can create a new column in a pandas DataFrame by applying a function to two existing columns on a row-by-row basis:
import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) def add(a, b): return a + b df['C'] = df.apply(lambda row: add(row['A'], row['B']), axis=1) print(df)The key steps are:
- Define the function that operates on the two columns
- Use
DataFrame.apply()and pass in the function. Specifyaxis=1to apply the function row-wise. - Assign the output series from
apply()to a new column in the DataFrame.
The
lambdafunction appliesadd()to the 'A' and 'B' columns for each row.The new 'C' column now contains the sum of 'A' and 'B' for each row. This allows you to easily create new columns by applying operations to existing columns in a vectorized manner.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.