I am using Python/Pandas to extract data from an excel file and do some processes but I am stuck dealing with this:
I have this data (is not formatted as a table) in my data frame:
column1 | column2 | column3 | column4 | column5 | column6 | column7 |
---|---|---|---|---|---|---|
Tesla Cars | Toyota Cars | |||||
SUV | SEDAN | TRUCK | SUV | SEDAN | TRUCK | |
Dealer NYC | 10 | 20 | 5 | 15 | 25 | 10 |
Dealer Texas | 20 | 30 | 10 | 25 | 35 | 15 |
And I would it to look this:
column1 | column2 | coulmn3 | column4 | column5 |
---|---|---|---|---|
SUV | SEDAN | TRUCK | ||
Dealer NYC | Tesla Cars | 10 | 20 | 5 |
Dealer NYC | Toyota Cars | 15 | 25 | 10 |
Dealer Texas | Tesla Cars | 20 | 30 | 10 |
Dealer Texas | Toyota Cars | 25 | 35 | 15 |
I tried to get it to work since Wednesday until Friday but I just could not figure out the logic for it.
It can be that I also have several car brands and all of them would be above the string “SUV” and the car types will always be SUV, SEDAN,TRUCK and the corresponding values under them.
I tried to go about by creating a nested dictionary, where I would save the string right above SUV as the “key” then SUV,SEDAN,TRUCK as the nested keys, and their values as the numbers that are under each of them respectively, it should have looked something like this:
brand_1 : { Tesla cars: {SUV: [10,20], SEDAN:[20,30], TRUCK:[5,10]}
brand_2: { Toyota_cars: {SUV:[15,25], SEDAN:[25,35], TRUCK:[10,15]}
Then unpack the main key(Tesla Cars, Toyota Cars) in a new column and the values of the nested keys( [10,20],[20,25], [5,10], [15,25], SEDAN[25,35], [10,15] in their respective columns. But of course it did not work.
I am sure I am overcomplicating things and that there is a much easier method and logic to achieve this, can you please guide me to the correct way to deal with such data?
I tried creating a nested dictionary with the car brand as the main key and the different type of cars as their nested keys with their values and then unpack but it did not work. My logic cannot create the correct dictionary, I guess I am not relating the keys and values correctly.
PepelearningPython is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.