简体   繁体   中英

How to divide first number in a pandas series with the sum of all the numbers in a series in Python

I have a pandas series which looks like this..

dish_name
Chiken Biryani    3
Mutton Biryani    1
Paneer Biryani    4
Paneer Pulav      2
sandwitch         2

I want to calculate 1st dish divide by rest of the dishes quantity..so it should be like.. first element (3/(3+1+4+2+2) then second element (1/(3+1+4+2+2) and so on till the last element.. Here is what I am doing

def dish_push(dish_data):
dish_number = len(dish_data)
for i in range(0,dish_number):
    dish = (dish_data[i])/(dish_data[0:dish_number].sum())
    print dish

But its not giving me desired results.. What I want is

dish_name
Chiken Biryani    0.25
Mutton Biryani    0.083
Paneer Biryani    0.33
Paneer Pulav      0.16
sandwitch         0.16

Is there something wrong with my logic? please help

Is this what you want?

print(s/s.sum())

Chiken Biryani    0.250000 
Mutton Biryani    0.083333
Paneer Biryani    0.333333
Paneer Pulav      0.166667
sandwitch         0.166667
dtype: float64

You can use python dict to achive this as below,

def dish_push(dish_data):
    dish_number = len(dish_data)
    total=0
    for key in dish_data:
        total+=dish_data[key]
    for key in dish_data:
        dish_val = (float(dish_data[key])/float(total))
        print key + " " + str(dish_val)

dish_data={"chicken Briyani":3,
            "Mutton Biryani":1,
            "Paneer Briyani":4,
            "Paneer Pulav":2,
            "sandwitch":2
          }
#main
dish_push(dish_data)

===================================

Paneer Briyani           0.333333333333
chicken Briyani           0.25
Mutton Biryani           0.0833333333333
sandwitch           0.166666666667
Paneer Pulav           0.166666666667

Here I am looping 2 times, 1st time to get count this code can still be simplified by using list comprehension i guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM