Skip to content
TheChatArchiveThe Chat Archive
chatgpt-4o-latest-20250326· OpenAIHugging Face LMArena Human Preference 140K

create pivot table in pandas with dataframe df, index = x, sum=y

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

    create pivot table in pandas with dataframe df, index = x, sum=y

  2. Assistant

    To create a pivot table in Pandas with a DataFrame df, using column x as the index and computing the sum of column y, you can use the pivot_table method as shown below:

    ✅ Example Code

    import pandas as pd
    
    # Sample DataFrame
    # df = pd.DataFrame({
    #     'x': ['A', 'B', 'A', 'C', 'B', 'A'],
    #     'y': [10, 20, 30, 40, 50, 60]
    # })
    
    # Create pivot table
    pivot = pd.pivot_table(df, index='x', values='y', aggfunc='sum')
    
    print(pivot)
    

    🔍 Explanation:

    • index='x': Groups the data by the values in column x.
    • values='y': Aggregates the data in column y.
    • aggfunc='sum': Sums the y values for each group in x.

    If you want the result as a flat DataFrame (not MultiIndex), and reset the index:

    pivot = pivot.reset_index()
    

    Let me know if you have multiple columns to group or want to use different aggregation functions!

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