-1

I have 2 questions: First, i have this data-frame:

data = {'Name':['A', 'B', 'C', 'A','D','E','A','C','A','A','A'], 'Family':['B1','B','B','B3','B','B','B','B1','B','B3','B'],
       'Region':['North', 'South', 'East', 'West','South', 'East', 'West','North','East', 'West','South'], 
        'Cod':['1','2','2','1','5','1','1','1','2','1','3'], 'Customer number':['A111','A223','A555','A333','A333','A444','A222','A111','A222','A333','A221']
        ,'Sales':[100,134,53,34,244,789,213,431,0,55,23]}

and i would like to have a column which returns a percentage of sales in a groupby of the other columns, like in the image below:

1

Second point is, if the percentage is 0% (like in the first row) i would like to use the same result based on a criterion, for example(if A222 is 0% use the result of A221).

desertnaut
  • 46,107
  • 19
  • 109
  • 140

2 Answers2

0

I think this is what you want:

import pandas as pd
df = pd.DataFrame(data)
granular_sum_df = df.groupby(['Name', 'Family', 'Region', 'Cod', 'Customer number'])['Sales'].sum().reset_index()
family_sum_df = df.groupby(['Name', 'Family'])['Sales'].sum().reset_index()
final_df = granular_sum_df.merge(family_sum_df, on=['Name', 'Family'])
final_df['Pct'] = final_df['Sales_x']/final_df['Sales_y']
Franco Piccolo
  • 4,217
  • 3
  • 17
  • 30
0

Well answer for question one could be:

#step  1 Import pandas
import pandas as pd

df=pd.DataFrame(data)

# step 2 printing the dataframe
df

# 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
npprices=df['percentage'].to_numpy()
npprices
#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:
  npprices[i]=npprices[i-1]

  #converting in to dataframe back
  percentage1=pd.DataFrame({'percentage2':npprices})

  # 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?

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388