Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-2.1· AnthropicHugging Face Arena Human Preference 55K

create a new column in pandas dataframe by applying a function to two columns for every…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4-0613’s answer.
  1. User

    create a new column in pandas dataframe by applying a function to two columns for every row

  2. Claude 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:

    1. Define the function that operates on the two columns
    2. Use DataFrame.apply() and pass in the function. Specify axis=1 to apply the function row-wise.
    3. Assign the output series from apply() to a new column in the DataFrame.

    The lambda function applies add() 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.