Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Pandas to find relative share of rooms in individual floors

I have a dataframe df with the following structure

   Floor         Room  Area
0      1  Living room    25
1      1      Kitchen    20
2      1      Bedroom    15
3      2     Bathroom    21
4      2      Bedroom    14

and I want to add a series floor_share with the relative share/ratio of the given floor, so that the dataframe becomes

   Floor         Room  Area  floor_share
0      1  Living room    18         0,30
1      1      Kitchen    18         0,30
2      1      Bedroom    24         0,40
3      2     Bathroom    10         0,67         
4      2      Bedroom    20         0,33

If it is possible to do this with a one-liner (or any other idiomatic manner), I’ll be very happy to learn how.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Current workaround

What I have done that produces the correct results is to first find the total floor areas by

floor_area_sums = df.groupby('Floor')['Area'].sum()

which gives

Floor
1    60
2    35
Name: Area, dtype: int64

I then initialize a new series to 0, and find the correct values while iterating through the dataframe rows.

df["floor_share"] = 0
for idx, row in df.iterrows():
    df.loc[idx, 'floor_share'] = df.loc[idx, 'Area']/floor_area_sums[row.Floor]

>Solution :

IIUC use:

df["floor_share"] = df['Area'].div(df.groupby('Floor')['Area'].transform('sum'))
print (df)
   Floor         Room  Area  floor_share
0      1  Living room    18     0.300000
1      1      Kitchen    18     0.300000
2      1      Bedroom    24     0.400000
3      2     Bathroom    10     0.333333
4      2      Bedroom    20     0.666667
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading