How to use pivot_table () to realize the data perspective function in Python
This article is to share with you about how to use pivot_table () in Python to achieve data perspective function, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Pivot_table
The pivot () function does not have data aggregation function. To achieve this function, you need to call the third top-level function in the Pandas package: pivot_table (). The project location in pandas is as follows:
Pandas
| |
Pivot_table ()
Construct a df instance as follows:
Call the following actions:
The parameter index indicates that An and B are row indexes, columns indicates that the value of column C is the column, the aggregate function is the sum, and values is the D column after the two axes (index and columns) are determined. The results are as follows:
Among them, the aggregate function can be extended more richly, using more than one. As shown below, D and E are selected for the intersection of the two axes, np.mean () is used for aggregation in column D, and np.sum, np.mean, np.max, np.min for column E
The results are as follows:
Function prototype
Fill_value: the fill value of the null value
Dropna: if all elements in a column are np.nan, whether to discard them
Margins: summary column, margins_name: summary name
The margins parameter defaults to False. If set to True, you will get a summary of each column, as shown in the following df instance
Set margins to True and summary line index to name and customize it to self_name:
Be careful
When margins is set to True, pandas version 0.22.3 only supports aggregate functions as a single element, but not list, as shown below:
An exception will be reported:
Through the pivot_table aggregation function source code (shown below), we find that it itself is implemented by calling groupby () and its agg ().
Grouped = data.groupby (keys, observed=False) agged = grouped.agg (aggfunc) the above is how to use pivot_table () to achieve data perspective in Python. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.