Created
October 16, 2024 01:00
-
-
Save sauravmishra1710/f9478e7e096e1ff87ceab77aa93f067a to your computer and use it in GitHub Desktop.
Category Column Mapping - I have a CSV with image name as a column and 7 other columns for the image category. The category column can have either 0 or 1 as value depending on what category the image belongs to. Create a new column 'category' using pandas to show what is the category of the image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
# Load your CSV file | |
df = pd.read_csv('your_file.csv') | |
# Assuming your category columns are named 'cat1', 'cat2', ..., 'cat7' | |
category_columns = ['cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7'] | |
# Create a new column 'category' based on the category columns | |
df['category'] = df[category_columns].idxmax(axis=1) | |
# Replace the index of the category with a more user-friendly name if necessary | |
# For example, if your categories are named 'Category1', 'Category2', etc. | |
category_mapping = { | |
'cat1': 'Category1', | |
'cat2': 'Category2', | |
'cat3': 'Category3', | |
'cat4': 'Category4', | |
'cat5': 'Category5', | |
'cat6': 'Category6', | |
'cat7': 'Category7' | |
} | |
df['category'] = df['category'].map(category_mapping) | |
# Save the updated DataFrame back to CSV if needed | |
df.to_csv('updated_file.csv', index=False) | |
# Display the updated DataFrame | |
print(df) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment