-
Notifications
You must be signed in to change notification settings - Fork 2
⚡️ Speed up function fix_nan_category by 137%
#30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -34,15 +34,17 @@ def flatten_column_name(item): | |||||||||||
|
|
||||||||||||
|
|
||||||||||||
| def fix_nan_category(df): | ||||||||||||
| for i in range(len(df.columns)): | ||||||||||||
| column = df.iloc[ | ||||||||||||
| :, i | ||||||||||||
| ] # We need to use iloc because it works if column names have duplicates | ||||||||||||
|
|
||||||||||||
| # If the column is categorical, we need to create a category for nan | ||||||||||||
| if column.dtype.name == "category": | ||||||||||||
| df.iloc[:, i] = column.cat.add_categories("nan") | ||||||||||||
|
|
||||||||||||
| # Collect indices of categorical columns to avoid repeated dtype checks | ||||||||||||
| categorical_indices = [ | ||||||||||||
| i for i, dtype in enumerate(df.dtypes) if dtype.name == "category" | ||||||||||||
| ] | ||||||||||||
| if not categorical_indices: | ||||||||||||
| return df | ||||||||||||
|
|
||||||||||||
| # Apply add_categories in bulk for categorical columns | ||||||||||||
| for i in categorical_indices: | ||||||||||||
| column = df.iloc[:, i] | ||||||||||||
| df.iloc[:, i] = column.cat.add_categories("nan") | ||||||||||||
|
Comment on lines
+45
to
+47
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Minor: simplify the assignment. Lines 33-34 can be combined into one statement without the intermediate variable. for i in categorical_indices:
- column = df.iloc[:, i]
- df.iloc[:, i] = column.cat.add_categories("nan")
+ df.iloc[:, i] = df.iloc[:, i].cat.add_categories("nan")📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||
| return df | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
|
|
||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick | 🔵 Trivial
Consider using pandas API for dtype checking.
dtype.name == "category"works butpd.api.types.is_categorical_dtype(dtype)is more idiomatic and robust.🤖 Prompt for AI Agents