Jack_T
Jack_T

Reputation: 91

Calculating percentage between two dataframes concatenated into one dataframe

If I have two dataframes (df1 and f2) and I join them into one dataframe (df3):

df3 = pd.concat([df1, df2])

Example dimensionality of df1, df2, and df3 are:

   df1 = (2, 1)
   df2 = (8, 1)
   df3 = (10, 1)

I would like to calculate the respective length percentage of df1 and df2 over df3. Output should be:

   df1 % over df3 = 20%
   df2 % over df3 = 80%

Is there a way to do this calculation in pandas? Thank you!

Upvotes: 1

Views: 161

Answers (1)

YOLO
YOLO

Reputation: 21719

You can do:

print(f"{len(df1)/len(df3):.2f}%") # 0.20%
print(f"{len(df2)/len(df3):.2f}%") # 0.80%

Here f corresponds to f-strings.

To get percentages use below:

print(f"{len(df1)/len(df3):.2%}") # 20.00%
print(f"{len(df2)/len(df3):.2%}") # 80.00%

From docs of mini string language

% - Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.

Upvotes: 1

Related Questions