chatgpt-4o-latest-20250326· OpenAI
LMArena Human Preference 140K
create pivot table in pandas with dataframe df, index = x, sum=y
- User
create pivot table in pandas with dataframe df, index = x, sum=y
- Assistant
To create a pivot table in Pandas with a DataFrame
df, using columnxas the index and computing the sum of columny, you can use thepivot_tablemethod 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 columnx.values='y': Aggregates the data in columny.aggfunc='sum': Sums theyvalues for each group inx.
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!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.