So my dataframe looks like this:
I am trying to find a simpler way to get the objects from a Groupby and then putting it in a dictionary.
I had to obtain the index and then do a for loop to get the exact string of each row in Product.
More details if needed: My goal was to find duplicate Order ID and then take the products from the column and add to dictionary with:
key = Product
value = no of times the Product is found to be ordered together
(I am not looking for ways to optimize finding duplicates, i know I could use df.duplicated )
Code:
for date, df in df1.groupby('Order Date'):
if df.Product.count() > 1:
indice = df.Product.index
for data in indice:
product = df.loc[data].at['Product']
#update dictionary counter
product_dict[product] = product_dict.get(product) + 1
else:
continue
for ease you can use this df instead. I listed as dictionary:
{'Order ID': ['147268', '148041', '149343', '149964', '149350', '141732', '149620', '142451', '146039', '143498', '141316', '144804', '144804', '145270', '142789'],
'Product': ['Wired Headphones', 'USB-C Charging Cable', 'Apple Airpods Headphones', 'AAA Batteries (4-pack)', 'USB-C Charging Cable', 'iPhone', 'Lightning Charging Cable', 'AAA Batteries (4-pack)', '34in Ultrawide Monitor', 'AA Batteries (4-pack)', 'AAA Batteries (4-pack)', 'Wired Headphones', 'iPhone', 'Google Phone', 'AAA Batteries (4-pack)']}
The expected output:
{'Wired Headphones': 8090, 'USB-C Charging Cable': 9425, 'Apple Airpods Headphones': 6374, 'AAA Batteries (4-pack)': 8266, 'iPhone': 3663, 'Lightning Charging Cable': 9074, '34in Ultrawide Monitor': 2500, 'AA Batteries (4-pack)': 8167, 'Google Phone': 3091, 'Macbook Pro Laptop': 1878, 'ThinkPad Laptop': 1605, '27in FHD Monitor': 3010, 'Bose SoundSport Headphones': 5459, 'Flatscreen TV': 1827, '27in 4K Gaming Monitor': 2457, 'LG Dryer': 257, '20in Monitor': 1635, 'LG Washing Machine': 268, 'Vareebadd Phone': 1120}