In pandas's unstack Times ValueError: duplicate entries error
Pandas is a basic numpy-based library tool for data analysis and processing in python. It is a basic entry tool in the field of python language data. Common uses include:
A provides advanced data structures and rich data manipulation API
B improves the efficiency of complex matrix operations (at present, the matrix here can be simply regarded as an Excel data table, which can be made up by yourself)
C provides data cleaning and processing functions
D help with data mining and analysis
Back to the point: the code is as follows (environment: anaconda3+python3)
When running the code:
Two important data structures of pandas: Series and DataFrame
Object method unstack (): the API of the Series object, which is used to convert the data type of Series to DataFrame type, because DataFrame provides far more data manipulation API than Series. (Series is treated as one-dimensional, DataFrame as high-dimensional data, analogy between one-dimensional array and high-dimensional array)
The data manipulated with unstack must be uniquely identified, and the print obj1 is as follows:
There is a repetition, and unstack cannot uniquely distinguish, so the conversion failure error ValueError: Index contains duplicate entries, cannot reshape. Solution: modify the letter index name or numeric index, as long as it can be uniquely identified, such as changing the duplicate 1 to 2 (not 3 here) or changing it to a letter.
Take the outer index of the hierarchical index as the row index of DataFrame, and the inner index of the hierarchical index as the row index of the hierarchical index. As a column index. The result is printed as follows:
Think about it: since you can use unstack () [unpack] to convert Series to DataFrame, what is the method of converting DataFrame to Series?
Answer: use stack () [package]