Pandas pivot table multiple values. x; pandas; dataframe; Share.
Pandas pivot table multiple values reset_index(). pandas pivot table on multiple columns. Here the aggregation using first is with the assumption that there are no duplicates. DataFrame( The aggfunc argument of pivot_table takes a function or list of functions but not dict. In [70]: pd. About; Products OverflowAI; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Columns refer to the metric or attribute that we want to analyze in the Pivot Table. Modified 6 years, 4 months ago. Python Pandas: how to only pivot certain columns while keeping others? 2. 602398 -0. How to pivot multiple columns. Python multiple pivot from the same column . Python - pivot DataFrame with multiple indexes on columns. This approach allows for a more detailed representation of the data, incorporating multiple dimensions into the The representation of pivot tabel not looks like something I looking for, to be more specific the order of the resulting rows. swaplevel(0,2, axis=1). pivot_table(data, values=None, index=None, columns=None, aggfunc=’mean’, fill_value=None, margins=False, dropna=True, margins_name=’All’) create a spreadsheet-style pivot table as a DataFrame. The following tutorials explain how to perform other common operations in pandas: Pandas: How to Create Pivot Table with Count of Values Pandas: How to Replace NaN Values in Pivot Table with Zeros Pandas: How to Convert Pivot Table to Create a Pivot Table with multiple columns Python Pandas - We can create a Pivot Table with multiple columns. Create a spreadsheet-style pivot table as a DataFrame. name}FY','')] = s1 x[(f'{x. pivot_table(df,index="CNTRY",columns="TYPE", values='VALUE'). Unpivot pandas DataFrame partly. I have df like below . Hot Network Questions Hit Lynel with ancient arrow and it vanished - did I kill it? What is the word for someone who follows instructions incorrectly but believes what they're doing is right? How many non-attacking grasshoppers on a chess board? Was trying to generate a pivot table with multiple "values" columns. loc[:, c <= 4]. 588972 2 thai 0. DataFrame. Community Bot. How do I create a pivot table with multiple If some column names are not strings, you can map the column names to strings and join them. Hot Network Questions In John 1:1-2, does "in the beginning" mean that the Son already existed or that he began to exist with God? How do I get the infinitive form of a verb? "to deceive" - Rev pandas pivot dataframe with multiple groupby. Follow edited Jun 1, 2018 at 9:03. Syntax. pivot_table(data, values=None, index=None, columns=None, aggfunc=’mean’, fill_value=None, margins=False, dropna=True, margins_name=’All’, observed=False) Purpose: Create a spreadsheet-style pivot table as a DataFrame. Example of Using Indexing and Multiple Columns in Pandas Pivot Table. sum(axis=1) #sum 1,2,3,4 months s2 = x. Pandas Pivot is essentially used for data transformation. RIP Tutorial. For pd. Any help would be much appreciated, thank you. out = df_res. sum()}) I am currently doing this through adding a conditional column and then summing it along with 'value' in pivot and then dividing, but my database is huge (1gb+) and there has got to be an easier way. df2. It provides an easy way to restructure and reorganize your data, converting it from a 'long' format to a 'wide' format, or vice versa. 710938 12352000 62938. To create a Pivot Table, use the pandas. 566261 0. 2. Flattening MultiIndex pivot table in Python pandas. Pandas pivoting more than one column in index. While columns added a horizontal dimension, we can also specify multiple indices when there is a logical hierarchy in our data. Here is an example that I want to create: Inputs are df1 and df2, res is the result I want to calculate from df1 and df2 import pa df1 = df. Uses unique values from specified index / columns to form axes of the resulting DataFrame. reindex(['mean','lo','hi'], level=2, axis=1)) Out[107]: type type1 type2 \ group group1 group2 Pandas pivot table for multiple columns at once. We can create a Pandas pivot table with multiple columns and return reshaped DataFrame. pivot_table (df, values=' col1 ', index=' col2 ', columns=' col3 ', aggfunc=' count ') Method 2: Pivot Table With Unique Counts. def f(x): #get all months and convert to integers numbers c = x. Once I have pivot table the way I want, I would like to rank the values by the columns. This is easy to do with a custom I am trying to sort this table first by IN_FID ascending from top to bottom, and then by Jurisdiction, ascending from left to right. 534509 0. Modified 3 years, 3 months ago. (Default is to hide empty entries). A workaround is to use pd. res = df. melt() and wide_to_long() : Unpivot a wide DataFrame to a long Create a spreadsheet-style pivot table as a DataFrame. Introduction to Pivot Tables in Pandas. Hot Network Questions How could a medieval town defend against sauropods? Applying for a PhD with the same researcher that 'rejected' you in the past What aspect of resetting a NES explains bits of game state being preserved? Can collapse of wave function change energy of the system? I want to create a pivot with average values over multiple tables. Use swaplevel, sort_index and reindex on the output of pivot_table. mean, or list of functions If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. Stack Overflow. pivot, for reasons unknown to me, don't work with a list of values for index. Example: pivot() for Multiple Values. See the example below: Say I want to sum the "Number_mentions" column for each value in the "Newspaper" column if the value of "Number_mentions" is above a threshold. By doing this, you don't need to reset the index. pivot_table(df, values=['C','D'],rows='B',cols='A'). Pandas: How can I move certain columns into rows? 1. You'd need to use aggfunc='first' with pivot_table to deal with strings as the default assumption is you aggregate with mean with pivot_table. aggfunc : function, default numpy. agg({'ind1': lambda x: ', '. df. Handle Missing Values With pivot_table() Sometimes while reshaping data using pivot_table(), missing values may occur in the pivot table. 2 12463634 E_REASON 010 12463634 IN_SCOPE Y 12463635 Would work, but down the line you may face problems , as you try accessing some columns with some way that is not 2D Column name Friendly. sum) Pivot = UNSPSC. pivot(index='searchTerm', columns='feature', values='score'). strip('_') for c in df2] If you want to chain the renaming method to pivot_table method to put it in a pipeline, you can do so using pipe and set_axis. Create a spreadsheet-style pivot table as a DataFrame. 409 2 2 gold badges 8 8 silver badges 20 20 bronze You can add parameter values: df = pd. 6k 68 68 gold badges 176 176 silver badges 279 279 bronze badges. If we omit the values argument in pivot(), it selects all the remaining columns (besides the ones specified index and columns) as values for the pivot table. 0 I am trying to do multiple rounds of pivot_table to turn my flat data into something I can use for a project. pivot_table to accomplish this but I can't seem to figure it out exactly. Indicator Country Year Value 1 An A tutorial on the basics of pandas pivot tables. str. 431068 0. 5 two bar 4 4. 00 NaN 0 3 2019-07-06 Pandas pivot table for multiple columns at once. 3. I would recommend using the more general version of pd. Hot Network Questions What is the current status in 2025 of the Everett-Chomsky controversy / debate regarding Universal Grammar? Identify this (contradictory and potentially mislabeled) electrical device Molecular orbitals for molecule C8F8 are not normalised to unity I wonder if pandas. pivot(index='CarModel', Learn pandas - Pivoting with aggregating. It will use all columns for values. It is a seemingly simple function but can produce very powerful analysis very quickly. shape) # One Dimensional Pivot Tables: A pivot table is a table of statistics that summarizes the data of a more extensive table (such as from a database, spreadsheet, or business intelligence program). Pivot tables are a quintessential tool for data analysis, allowing for the summarization of data. Let's create a DataFrame (df) with columns Name, Subject, Score, and Grade. Pandas pivot table for multiple columns at once. " You can create the pivot table before splitting by Location. g. How to unpivot pandas dataframe. Pivot tables allow you to perform common aggregate statistical calculations such as sums, counts, averages, and so on. 294k If you have multiple data columns, calling pivot without the values columns should give you a pivoted frame with a MultiIndex as the columns: In [3]: df Out[3]: columns data1 data2 index 0 a -0. It is important that the values have to be in order, so table = pivot_table(df, values='D', rows=['A', 'B'], cols=['C']) table. The dropna argument specifies whether to remove the columns whose entries are all NaN. Thinking maybe I could concat get_dummies for each column then groupby name and sum, but feel like pandas prob has a better way. 07 2 item_0 2012-12-03 00:00:00 0. 1 1 1 silver badge. I found this almost similar problem (Pivot Tables or Group By for Pandas?) but as I understand it doesn't work for multiple columns. For example, we can add a date dimension to Creating a Multi-level Pivot Table with Pandas DataFrame. Pivot based on the index values instead of a column. values. Ask Question Asked 5 years, 7 months ago. Column or columns to The size function gives the counts you want, you would want to fill non-counted values with 0, and specify the columns and index you want. pivot. As an example, the below code creates a bar chart 1. pivot_table:. As per pandas official documentation. reset_index() pivot table in pandas with multiple columns. The following example shows how to use this syntax in from pandas import pivot_table import numpy as np UNSPSC = pivot_table( analysis, values = 'Extended Price', rows = 'UNSPSC', aggfunc = np. I've attached an im You can use the following syntax to create a pivot table in pandas and provide multiple values to the aggfunc argument:. 5. 0 NaN 4. 18. Pivot table with Multi Index Dataframe . Pandas’ pivot table functionality brings this power into the Python environment pivot does not accept list of columns as index so you need to use pivot_table. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog Create Pandas Pivot Table Group the Data into Pivot Table using Index Param. Pivot table in Pandas. 593750 12352100 165760. Pivot some rows to new columns in DataFrame. 572405 0. I have a table in csv format that looks like this. get_level_values(1). I am learning pandas and was implementing pivot_table. – I'm wanting to pivot the type column while setting the values within to true or false so that the end result looks like so: Desired outcome dataframe. 2 101 11/1/3 3 2. 1. have a pandas dataframme with columns name , school and marks. Parameters: data DataFrame values list-like or scalar, optional. This is where I'm at: import pandas as pd import numpy as np df = pd. Say I have the following data frame: id date day val 101 11/1/1 1 2. pivot_table# pandas. Ask Question Asked 6 years, 4 months ago. Pivot with multi index in Pandas data frame. reset_index() print (df1) feature searchTerm a b c 0 chinese 0. Follow edited Jan 4, 2017 at 23:54. Python - trouble pivoting, grouping, and summing dataframe columns. This format seemed to work previously: Multiple AggFun in Pandas. plot() to the end of your pivot table code will create a plot of the data. 57 17640 1 2019-07-06 AdMob 519. In Pandas, we can use the pivot_table() function to create a Pivot Table with indexing and columns. e. join(map(str, c)). Levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. table = df. To group the data into a pivot table using the index parameter, you specify the column(s) you want to use as the index in the resulting pivot table. Hot Network Questions Problem with VScode automatic uninstalled extension (Material theme) Would CSRF protection be pointless on pandas. 1 101 11/1/2 2 2. pass parameter fill_value=0 to fill up NaN values as 0; Then locate Location from the pivot table by The values are simply concatenated into one row in order. I have created a pivot table with multiple index as follows: import pandas as pd import numpy as np df1 = pd. pivot_table (df, values=' col1 ', index Pandas pivot table for multiple columns at once. Additional Resources. 0 foo 28 25. Often, the information a pivot table produces reveals trends and other You want to stack (and not unstack):. pandas pivot multi-indexed columns. See docs for more details. Viewed 725 times 1 . This summary might include sums, averages, Can I do this for two separate some_values, and add them together? I have the below working correctly for "Civilian Labor", but I want to do the same for "Labor Overhead" and add them together for a new column called "Total Labor. (In simple words, similar to the pivot we usually get in excel). pivoteCols = df. res = ( data. 499068 0. name school marks tom HBS 55 tom HBS 55 tom HBS 14 mark HBS 28 mark HBS 19 lewis HBS 88 How to df. Modified 5 years, 7 months ago. ix like here (define aggfunc for each values column in pandas pivot table) the only option? python; python-3. columns = ['_'. 0. We took a look at how MultiIndex and Pivot Tables work in Pandas on a real world example. 0 foo 4 4. Pandas PivotTable. Transposing multi index dataframe in pandas. Let’s go through an example to see how to use indexing and multiple columns in a Pivot Table. Pivot table: “Create a spreadsheet-style pivot table as a DataFrame”. Syntax: pandas. assign(Values=lambda x: x['NumericalValues']. Pandas pivot tables can be used in conjunction with the pandas plotting functionality to create useful data visualizations. asked Aug 15, 2012 at 17:04. I looked into pivot_table and know I can use new_ds = pd. Is Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company A pivot table is a data analysis tool that allows you to take columns of raw data from a pandas DataFrame, summarize them, and then analyze the summary data to reveal its insights. pivot_table(values='value', index=['stream_name', 'preferred_timestamp', 'internal_timestamp', 'value_id']) stream_name preferred_timestamp internal_timestamp value_id In other words, I would like, for each id, the number of occurences of each value in col1, col2 and col3. I want to aggregate one column with a pandas pivot table, but the custom aggregation should be conditional on a different column in the dataframe. pivot(), which is pd. pivot_table to One of the primary tools provided by Pandas for creating pivot tables is the pivot_table() function. My dataframe currently looks like: ID FIELD VALUE 12463634 TEST 22. reset_index() print (df) TYPE CNTRY Advisory Advisory1 Advisory2 Advisory3 0 FRN NaN 2. How to pivot table in pandas on multiple columns? 0. name}YTD','')] = Pandas Pivot and Un Pivoting a table. 3 102 11/1/2 1 3. ix['one', 'A'] python; indexing; pivot; pivot-table; pandas; Share. You can use one of the following methods to create a pivot table in pandas that displays the counts of values in certain columns: Method 1: Pivot Table With Counts. x; pandas; dataframe; Share. Date Ad_Source Revenue eCPM Impressions 0 2019-07-06 AdColony 50. 62 269. <c01 value>_<c02 value>_<v1> I'd like to convert a Pandas DataFrame that is derived from a pivot table into a row representation as shown below. I've tried both the pivot and pivot_table Pandas functions and even tried to manually pivot the tables by using 'set_index' and 'stack' but it's not quite how I want it. 880927 0. 332031 This article focuses on manipulating data in Python with the Pandas library to create multi-dimensional pivot tables. I would like to transpose the table so that the values in the indicator column are the new columns. Pivot pandas dataframe to have multi-indexed columns. You can It can be created using the pivot_table () method. 982524 x 1 a 0. | Video: codebasics How to Plot with Pandas Pivot Table. asked Mar 20, 2016 at 13:56. columns = pivoteCols print(df. They enable the aggregation of data points based on columns and calculation of statistics such as counts, sums, and averages. Learn pandas - Pivoting with aggregating. reset_index(drop=True) clean_tbl: Country 2005 2006 0 Afghanistan 16 9 1 Albania 17 19 2 Algeria 11 7 3 Andorra 5 12 You can use the following basic syntax to create a pivot table in pandas that displays the sum of values in certain columns: pd. . alexhli alexhli. I'm trying to create a calendar that rolls up information across a catalog of projects and organizes it chronologically and by project type. Pandas Pivot table with multi index. pivot_table (index=[' team '], values=[' points ', ' assists '], aggfunc=' sum ') #view pivot table print (df_pivot) assists points team A 14 18 B 19 26 C 25 23 By default, pandas sorts the rows of the pivot table in alphabetical order based on the value in the index column, which happens to be the team column. 84 3 item_1 2012-12-02 00:00:01 0. pivot_table(index="PAR NAME",values=["value"],aggfunc={'value':lambda x: (x. DataFrame({'Team ID': {0: pandas pivot table on multiple columns. Brief Overview of Pandas Pivot. Let's see an example. pivot_table can accept two columns at once and process them separately instead of hierarchically. pivot is a simple reshaping of the data, which is what you want here. pandas: How to pivot multiple columns and calculate their sum? 0. stack() Out[70]: C D B A one bar 2 2. 031250 12190000 68791. In this example, the pandas DataFrame (df) is transformed into a multi-level pivot table, using ‘A’ as the index, ‘B’ as the columns, and extracting values from both columns ‘C’ and ‘A’ to fill the cells. sort_index(1) . The levels in the pivot table will be stored in MultiIndex objects (hierarchical pandas pivoting table always sorts index and column names. Pivoting DataFrame with multiple columns for the index. pivot_table(index=['u_id', 'date'], columns='social_interaction_type_id', values='Total_Count', aggfunc='first'). Follow edited May 23, 2017 at 12:00. df3 = (df2. Modified 6 years, 11 months ago. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to sum or avg both columns but instead I want sum of one column while mean of the other one. Imagine having a dataset with sales information including dates, products, and regions. Hot Network Questions Did Mehmet Ali Agca publish a new book about John Paul II assassination attempt? How to give a heads up to people from a different company that the CEO of the company I work for has anger issues? I am a new user to Pandas and I love it! I am trying to create a pivot table in Pandas. At first, import the required library −import pandas as pdCreate a DataFrame with Team records −dataFrame = pd. Getting started with pandas; Awesome Book; Awesome Community; Awesome Course; Awesome Tutorial; Awesome YouTube; Analysis: Bringing it all together and making decisions; Appending to DataFrame; I would have thought that test. pivot_table(data, index = 'InMonth', columns= 'OutMonth', aggfunc= 'count')['ID'] I need a column towards the end of pivot table having the row totals. Viewed 7k times 3 . pivot(index='Country',columns='Year',values='Value') Table: Year Country 2005 2006 0 Afghanistan 16 9 1 Albania 17 19 2 Algeria 11 7 3 Andorra 5 12 4 Angola 6 18 I want 'Year' to be 'index': clean_tbl = table. pivot_table (data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All', observed=<no_default>, sort=True) [source] # Create a spreadsheet-style pivot table as a DataFrame. join('_') pivoteCols = pivoteCols. pivot() and pivot_table(): Group unique values within one or more discrete categories. The desired output is a pivot table with the sales aggregated by product and region Add Multiple Indices to Pandas Pivot Tables. pivot_table(dataset, index='id') to aggregate by the ID, but I want to be selective (not including y for all rows, and in reality there's other garbage data I do not want). apply:. columns #create pivot table df_pivot = df. Viewed 6k times 2 . One of the challenges with using the panda’s pivot_table is making sure you understand your data and what questions you are trying to answer with the pivot table. In pandas, this would look like this: import pandas a In this article, we will learn how to use pivot_table() in Pandas with examples. 35. I've been using Pandas and have been unable to get the basic structure right. Generalization of pivot that can handle duplicate values for one index/column pair. While implementing the example given in pivot_table documentation : raw_data = {'A':['foo','foo','foo','foo','foo' Skip to main content. 79 370855 2 2019-07-06 AppLovin 0. Ask Question Asked 6 years, 11 months ago. Use the pandas. The best solution here, if you want to keep the index, would be to tell pandas to merge on the index on the left and right tables. 586020 0. pivot_table is more when you want to aggregate (or reshape with MultiIndices). Simply adding . pivot. sum() if x["DESTCD"]=="E")*100. When I create a pivot table on a dataframe I have, passing aggfunc='mean' works as expected, aggfunc='count' works as expected, however aggfunc=['mean', 'count'] results in: AttributeError: 'str' object has no attribute '__name__. Such missing values or NaN values can be handled in a pivot_table() operation using the arguments fill_value and dropna. You need post-processing the output if you want as your desired output. Improve this question. 5,509 4 4 gold badges 40 40 silver badges 61 61 bronze badges. 238849 How to pivot pandas data frame into multi level columns. 818551 y 2 b -0. 0): df1 = df1. The Creating Pivot Table with Multiple Columns using Pandas Pivot Table for Students Report. pivot_table. Pivoting one dataframe column with associated values to create multiple columns. 441617 Last you can remove columns name by rename_axis (new in pandas 0. whytheq whytheq. Moreover, you can also reorder column levels using reorder_levels, e. I have a pandas dataframe with data like this: df: item day time data 0 item_0 2012-12-02 00:00:01 0. pivot_table(data, index=None) Parameters: data : DataFrame index: column, Grouper, array, or list of the previous. groupby('ind0'). rename_axis(None, axis=1). join(x. Ask Question Asked 3 years, 3 months ago. I would suggest, use. Conclusion. fillna(x['CategoricalValues'])) . pivot_table (df, values=' col1 ', index=' col2 ', columns=' col3 ', aggfunc=' sum ') The following example shows how to use this syntax in practice. Example: Create Pandas Pivot Table With Sum of Values Aggregating multiple string values in Pandas pivot table. pivot_table(), like so: x = pd. rename_axis(None, axis=1) #pandas bellow Note: You can find the complete documentation for the pandas pivot_table() function here. pivot_table (data, index=None) Parameters: index: It is the feature that allows you to group your data. 0/x. It can be created using the pivot_table() method. pivot_table(index='name',columns=['actfig','car','pet'],aggfunc='size']) would do it, but it gives me some weird multi-level columns. set index with index=['Location', 'Status']; pass parameter dropna=False to allow all categories to show up for all Location and all Status even when empty. 484375 12352300 96212. Unpivot in pandas using a column that have mutiple value Is using . pivot_table to create a spreadsheet-style pivot table as a DataFrame. 12. 3 I want the result to be like this: Pivot. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame. index: It is the feature that allows you to group your data. unstack. pivot_table: pandas - how to transform pivot output for data frame and access active_def = pd. For example, one field for the year, one for the month, an 'item' field which shows 'item 1' and 'item 2' and a 'value' field with numerical values. 1 102 11/1/3 2 3. pandas pivot table on multiple Use pivot instead of pivot_table. unique()), 'X':'sum', 'Y':'sum'}) Or if you have multiple columns that you need to do the same function on, you could also use pd. Viewed 2k times 2 . Since you specify only index parameter, the rest of columns which are columns last_year, next_year are used as values for aggregation. You can also reshape the DataFrame by using stack and unstack which are well described in Reshaping and Pivot pandas pivot table on multiple columns. pivot_table (index=' col1 ', values=' col2 ', Reshape data (produce a “pivot” table) based on column values. pivot_table with aggfunc='first':. 0 NaN 3. stack() and unstack() : Pivot a column or row level to the opposite axis respectively. >>> df. I. reshape(len(pivoteCols)) df. 23 361. , Pandas thinks you want to apply sum function on values of columns last_year, next_year. 489369 1 pizza 0. DataFrame(data = {'Customer':['Tom Ford','Susan Mock','Tom Ford','Tom Ford','Donale Fucc pivot; pivot-table; pandas; Share. This method is a highly customizable way to aggregate data. By manipulating given index or column values we can reshape the data based on column values. For each year is possible create new columns in custom function, so in ouput is also 2020FY columns in GroupBy. astype(int) #sum all values s1 = x. to_series(). how to create the pivot table in pandas with From your data, as you have a value either in 'NumericalValues or 'CategoricalValues', so you can create a column that combine all the information from both column with fillna, then use the pivot as you did. pivot_table (index=' col1 ', values=' col2 ', aggfunc=(' sum ', ' mean ')) This particular example creates a pivot table that displays the sum and the mean of values in col2, grouped by col1. pd. I can`t figure out how to change it in proper way. I was able to pivot the table and sort by IN_FID, but how do I add a second sort from left to right. pandas. This function does not I would like to run a pivot on a pandas DataFrame, with the index being two columns, not one. Hot When you don't specify values and columns parameters in pivot_table. DataFrame. The Data. As per the docs, optional index must be a string or object. 0 1 IND 1. order(ascending = False) UNSPSC 12352200 350045. pandas pivot multi-indexed columns . sum(axis=1) x[(f'{x. Similarly a row towards the end having the column totals and one cell having sum of all the values in a table. You need to analyze sales trends across different products and regions over time. Tags; Topics ; Examples; eBooks; Download pandas (PDF) pandas. Since all columns of df are all Python : Pandas pivot table for multiple columns at once which has duplicate values. 2 102 11/1/4 3 3. pivot_table(df, index = 'event', columns = 'date', values = 'count') You will get: date 01/01/2017 01/11/2016 01/12/2016 event 'defense' 245 226 246 'strike' 1592 1544 1524 Next, you can get rid of the 'date' string by setting: x. The levels in the pivot table of pandas will be stored in MultiIndex objects (hierarchical indexes) on the index I am trying to pivot a table on 2 value columns, apply some user defined function on the pivotted dataframe and then unpivot (stack in pandas). I'm thinking that I need to somehow use pd. Here is some sample data organized similarly to how it's coming out of the database. 81 1 item_0 2012-12-02 00:00:02 0. piRSquared . Unpivot df columns to multiple columns and rows. Pivot without aggregation that can handle non-numeric data. Moberg. Calculated column in python pivot table. Returns: You can use the following syntax to create a pivot table in pandas and provide multiple values to the aggfunc argument: df. 47 The combination of You could reset_index of df_res and groupby "ind0" and using agg, use different functions on columns: joining unique values of "ind1" and summing "X" and "Y". columns. 0 NaN And for remove columns name rename_axis: pandas pivot table on multiple columns. azzibr agnaqlnf fvf hhp caolkdj qywk myksqs xcrmta mcgwox crvr kuq dfeajhdc prdyj wttnw wwrd