Replacing values in a specific DataFrame column using a dictionary
📁 python
Need to replace values in a specific DataFrame column using a dictionary, and if the dictionary key is not found, delete the entire row from the DataFrame.
I was able to accomplish the task like this:
dict1 = {'Car': 'c', 'Motorcycle': 'mt', 'Truck': 'tr'}df = pd.DataFrame({'Product': 'Truck Motorcycle Car Car Tire Wheel Truck'.split(), 'Price': [10000, 5000, 23000, 15000, 500, 300, 8000]})d import copydict_all = copy.deepcopy(dict_1)for loop_dict in dict_2, dict_3: for k, v in loop_dict.items(): try: dict_all[k].extend(v) except KeyError: dict_all[k] = vIf preserving the original dict_1 is not needed, you can avoid deep copying it. The exception handling is needed in case dict_1 does not have some keys that appear in other dictionaries.
Log in to leave an answer