Comments (2)
import pandas as pd
# Create DataFrame
df = pd.DataFrame([[1, 2, 'March'],[5, 6, 'Dec'],[3, 4, 'April']], columns=['a','b','month'])
# Define custom_dict
custom_dict = {'March': 0, 'April': 1, 'Dec': 3}
# Convert 'month' column to Categorical with custom order
df['month'] = pd.Categorical(df['month'], categories=custom_dict.keys())
# Sort DataFrame based on the custom order
df.sort_values(by='month', key=lambda x: x.map(custom_dict))
from pandas.
To be more specific, sort_values
doesn't respect the key
parameter for categorical series.
Sorting does work as expected if the categorical is ordered using the ordered
param:
import pandas as pd
df = pd.DataFrame([[1, 2, 'March'],[5, 6, 'Dec'],[3, 4, 'April']], columns=['a','b','month'])
df['month_cat_ordered'] = pd.Categorical(df.month, ['March', 'April', 'Dec'], ordered=True)
df.sort_values('month_cat_ordered')
a | b | month | month_cat_ordered | |
---|---|---|---|---|
0 | 1 | 2 | March | March |
2 | 3 | 4 | April | April |
1 | 5 | 6 | Dec | Dec |
Mapping an unordered categorical as in the original example maps the old categories to the new categories but doesn't reorder the new categories. This is possible to implement this reordering in Categorical.map
but would come at a performance cost and it isn't immediately clear it's worth it.
from pandas.
Related Issues (20)
- BUG: read_parquet converts all digits strings to int HOT 2
- Make specific pandas dataframe column immuteable / not changeable HOT 4
- BUG: df.drop_duplicates fails if there is only a single row HOT 3
- Potential regression with PR "PERF: Eliminate circular references in accessor attributes (#58733)" HOT 1
- ENH: support parquet's enum type using Categorical when (de)serializing HOT 3
- ENH: generalize `__init__` on a `dict` to `abc.collections.Mapping` and `__getitem__` on a `list` to `abc.collections.Sequence` HOT 10
- ENH: Add a Series method which checks whether a Series is constant HOT 2
- BUG: df.agg with pd.NamedAgg axis=1 unsupported, but errors differently depending on contents of index HOT 1
- BUG: Segmentation Fault when importing Pandas in python 3.10.14 HOT 3
- BUG: df.agg with df with missing values results in IndexError HOT 3
- BUG: Groupby transformation (cumsum) output dtype depends on whether NA is among group labels HOT 7
- DOC: Docstrings missing from .py files in Sphinxext docs folder HOT 7
- BUG: Lookup by datetime in timestamp index does not work HOT 1
- DOC: Insufficient Project Background Information HOT 2
- BUG: pd.Index.Intersection fails with multiple data frames HOT 3
- BUG: pd.concat fails with large index values when using ArrowDtype
- BUG: Importing Pandas takes 30 seconds HOT 1
- DOC: Enhance the docstrings to provide more detailed explanations for the functions and their parameters in Common.py HOT 3
- Reduce redundancy: Common.py HOT 1
- ENH: add `atol`, `rtol` and `check_exact` to the Object.compare() method HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pandas.