how do i calculate a percentage of our population using a panda?

Well answer for question one could be:

#step  1 Import pandas
import pandas as pd


# step 2 printing the dataframe

# step 3 Calculating the pecentage:

df['percentage of sales'] = (df['Sales'] / df['Sales'].sum())*100

# step 4 :joining this table percentage to the main dataframe
pd.concat([df, df[['percentage of sales ']]], axis=1, sort=False)

Answer for question 2: its depends, what is the condition you want to do.

assumming the logic : enter image description here

that is one way ,

but the easy way to answer question 1 and 2 is to convert dataframe into a numpy array then do the operation , and then bring it back to dataframe. 1 check this answers: Add column for percentage of total to Pandas dataframe

#Converting the percentage column to numpy array
#loop through the rows and fill the row next row with value from previous row, ASSUMING previous row is not zero.

 for i in range(len(npprices)):
  if npprices[i]==0:

  #converting in to dataframe back

  # the joing this percentage row to to dataframe

  df2i=pd.concat([df, percentage1[['percentage2']]], axis=1, sort=False)

enter image description here

NOTE I added it twice, by mistake. But of course, there could be other easier approach, I hope this helps

Some answers: I used:

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top