Home > database >  Is there a simpler way to write this python pandas and for loop code?
Is there a simpler way to write this python pandas and for loop code?

Time:10-19

Is there simpler way to write the following code snippet in python?

The code is attempting to go through a base list of fruits which appear more than once with different prices and understand the mean prices on a per fruit basis. The results of this is then assigned to a dictionary.

The dataframe is consisting of the fruit name and prices of these fruit. This is called "fruits_list".

chosen_fruits = [ "orange", "apple", "kiwi" ]

fruit_total_data = {}

for item in chosen_fruits:
    population = fruits_list[fruits_list["fruit"] == item]
    pop_list = fruits_list["fruit"].value_counts()
    pop_list_price_sum = fruits_list["price"].sum() 
    pop_list_count = pop_list[0]
    mean = pop_list_price_sum / pop_list
    mean_take = mean[0]
    fruit_total_data[item] = mean_take

This seems to work but feels like there could be a more succinct way to code for this. Particularly with respect to the way the mean values are being calculated for the chosen fruits.

CodePudding user response:

Consider using Pandas Groupby and aggregation.

  • Related