Create all pairs combinations of columns names, loop and divide to new columns:

from  itertools import combinations

for a, b in combinations(df.columns, 2):
    df[f'{a}/{b}'] = df[a].div(df[b])

Or use list comprehension, join together by concat and add original columns by join:

df = df.join(pd.concat([df[a].div(df[b]).rename(f'{a}/{b}') 
                         for a, b in combinations(df.columns, 2)], 1))

print (df)
   x1  x2  x3  x4     x1/x2     x1/x3     x1/x4     x2/x3     x2/x4     x3/x4
0   4   7   1   5  0.571429  4.000000  0.800000  7.000000  1.400000  0.200000
1   5   8   3   3  0.625000  1.666667  1.666667  2.666667  2.666667  1.000000
2   4   9   5   6  0.444444  0.800000  0.666667  1.800000  1.500000  0.833333
3   5   4   7   9  1.250000  0.714286  0.555556  0.571429  0.444444  0.777778
4   5   2   1   2  2.500000  5.000000  2.500000  2.000000  1.000000  0.500000
5   4   3   0   4  1.333333       inf  1.000000       inf  0.750000  0.000000
Answer from jezrael on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pandas - creating new column with proportion/ratio from criteria/other cols
r/learnpython on Reddit: Pandas - Creating new column with proportion/ratio from criteria/other cols
January 26, 2024 -

Hi guys,

Fairly new to python - i'll try to be clear as I can

I have a dummy DF with some columns of appointments in healthcare - Surgeon, Conversion (1/0 or Yes/No)

I want to create a new column with "Conversion Rate" i.e. what % of the Surgeon's appointments resulted in a Conversion (1/True)

In plain english that looks like - if surgeon matches the one highlighted, return sum (Conversion) / count (Surgeon) but i'm struggling to get that delivered + applied via a function.

Here's my rough stab below but any thoughts/advice appreciated!

I am using pandas to do this and I do have other columns so I need to create a new column only with this rather than any over-arching DF operations. So if the surgeons name appeared 17 times I want the conversion rate column to show the same rate for that surgeon each time.

def convrate(surgeon):

for surgeon in df['Surgeon']:

ConvPts = 0

Non-Conv== 0

if df['Preop'] == 1:

if df['Conversion'] == 1:

ConvPts += 1

else:

Non-Conv += 1

return ConvPts / (ConvPts + Non-Conv)

Discussions

python - How to calculate ratio of values in a pandas dataframe column? - Stack Overflow
I'm new to pandas and decided to learn it by playing around with some data I pulled from my favorite game's API. I have a dataframe with two columns "playerId" and "winner" lik... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python 3.x - Pandas Group-By and Calculate Ratio of Two Columns - Stack Overflow
I'm trying to use Pandas and groupby to calculate the ratio of two columns. In the example below I want to calculate the ratio of staff Status per Department (Number of Status in Department/Total N... More on stackoverflow.com
๐ŸŒ stackoverflow.com
February 10, 2020
pandas - Adding new column in dataframe by taking ratio of two existing columns - Stack Overflow
I want to create a new column in dataframe by taking a ratio of two existing columns. Following code works but it does not retain the column df[price_per_sqft]. df['price_per_sqft'] = (df['SalePr... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to find ratio of multiple columns in pandas? - Stack Overflow
I have columns like total_balance, b1_amt, b2_amt, b3_amt, b4_amt, b5_amt and there are more than 100 columns in all - how can I find ratio of each column in new columns? For example I tried ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 22, 2018
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ divide-a-dataframe-in-a-ratio
Divide a DataFrame in a ratio | GeeksforGeeks
August 17, 2020 - Divide a Pandas Dataframe task is very useful in case of split a given dataset into train and test data for training and testing purposes in the field of Machine Learning, Artificial Intelligence, etc. Let's see how to divide the pandas dataframe randomly into given ratios.
Top answer
1 of 2
11

I think you need convert string columns to float or int, because their type is string (but looks like numbers):

Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(float)
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(float)

Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(int)
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(int)

Sample:

import pandas as pd

Good_apples = ["10", "20", "3", "7", "9"]
Total_apples = ["20", "80", "30", "70", "90"]
d = {"Good_apples": Good_apples, "Total_apples": Total_apples}
Apple_farm = pd.DataFrame(d)
print Apple_farm 
  Good_apples Total_apples
0          10           20
1          20           80
2           3           30
3           7           70
4           9           90

print Apple_farm.dtypes
Good_apples     object
Total_apples    object
dtype: object

print Apple_farm.at[0,'Good_apples']
10

print type(Apple_farm.at[0,'Good_apples'])
<type 'str'>
Apple_farm['Good_apples'] = Apple_farm['Good_apples'].astype(int)
Apple_farm['Total_apples'] = Apple_farm['Total_apples'].astype(int)

print Apple_farm.dtypes
Good_apples     int32
Total_apples    int32
dtype: object

print Apple_farm.at[0,'Good_apples']
10

print type(Apple_farm.at[0,'Good_apples'])
<type 'numpy.int32'>
Apple_farm['Perc_Good'] = (Apple_farm['Good_apples'] / Apple_farm['Total_apples']) *100

print Apple_farm
   Good_apples  Total_apples  Perc_Good
0           10            20       50.0
1           20            80       25.0
2            3            30       10.0
3            7            70       10.0
4            9            90       10.0
2 of 2
0

This code may helps you :

revenue_per_countries = df.groupby(["Country"])["Amount"].sum().sort_values()

revenue_per_countries = pd.DataFrame(revenue_per_countries)

revenue_per_countries['percent'] = revenue_per_countries['Amount']/revenue_per_countries['Amount'].sum()*100

revenue_per_countries = revenue_per_countries.sort_values(by=['percent'], ascending=False)

revenue_per_countries = revenue_per_countries.head(15)

revenue_per_countries.head(15)
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-create-a-column-with-ratio-of-two-columns-based-on-a-condition-in-r
How to create a column with ratio of two columns based on a condition in R?
x1 x2 Ratio_x1_x2 1 0 0 NaN 2 2 6 0.3333333 3 3 1 3.0000000 4 3 0 Inf 5 4 2 NA 6 2 1 2.0000000 7 3 2 1.5000000 8 3 3 1.0000000 9 2 0 Inf 10 3 3 1.0000000 11 0 5 0.0000000 12 2 1 2.0000000 13 4 1 NA 14 2 1 2.0000000 15 4 0 NA 16 1 2 0.5000000 17 1 2 0.5000000 18 3 2 1.5000000 19 6 4 NA 20 1 0 Inf
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ pandas โ€บ python-pandas-data-frame-exercise-38.php
Pandas: Divide a DataFrame in a given ratio - w3resource
Write a Pandas program to divide a DataFrame in a given ratio. Sample data: Original DataFrame: 0 1 0 0.316147 -0.767359 1 -0.813410 -2.522672 2 0.869615 1.194704 3 -0.892915 -0.055133 4 -0.341126 0.518266 5 1.857342 1.361229 6 -0.044353 -1.205002 7 -0.726346 -0.535147 8 -1.350726 0.563117 9 1.051666 -0.441533 70% of the said DataFrame: 0 1 8 -1.350726 0.563117 2 0.869615 1.194704 5 1.857342 1.361229 6 -0.044353 -1.205002 3 -0.892915 -0.055133 1 -0.813410 -2.522672 0 0.316147 -0.767359 30% of the said DataFrame: 0 1 4 -0.341126 0.518266 7 -0.726346 -0.535147 9 1.051666 -0.441533
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ pandas-groupby-and-aggregate-two-columns-for-respective-totals-then-calculate-ratio
Python DataFrame GroupBy Two Columns and Count: A Complete Guide for 2026
December 7, 2025 - Grouping data by multiple columns is one of the most powerful operations in pandas, enabling you to analyze complex datasets by splitting them into meaningful subsets. When you need to count occurrences or aggregate values across two columns simultaneously, pandas GroupBy becomes indispensable. This guide covers the complete methodology for grouping by two columns, counting combinations, aggregating multiple columns for distinct totals, and calculating ratios...
๐ŸŒ
DataCamp
campus.datacamp.com โ€บ courses โ€บ analyzing-social-media-data-in-python โ€บ twitter-networks
Ratios | Python
# Calculate in-degrees and store in DataFrame degree_rt = pd.DataFrame(list(____.____()), columns = column_names) degree_reply = pd.DataFrame(list(____.____()), columns = column_names) # Merge the two DataFrames on screen name ratio = ____.____(____, on = 'screen_name', suffixes = ('_rt', '_reply')) # Calculate the ratio ratio['ratio'] = ____ / ____ # Exclude any tweets with less than 5 retweets ratio = ratio[ratio['degree_rt'] >= 5] # Print out first five with highest ratio print(ratio.sort_values('ratio', ascending = False).head())
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 2748074 โ€บ i-cannot-figure-out-what-do-the-ask-me-to-output
I cannot figure out what do the ask me to output | Sololearn: Learn to code for FREE!
For your code all you need to do is add a new column 'ratio' to the dataframe df that is equal to the ratio of deaths per cases. (Divide deaths by cases). Then output the dataframe row where the ratio is equal to the max() for the dataframe.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 54752750 โ€บ calculate-ratio-with-pandas โ€บ 54752998
python - calculate ratio with pandas - Stack Overflow
"g" is a name of columns or a dataframe? 2019-02-18T18:05:31.927Z+00:00 ... I defined g in my answer. g = df.status.eq('Won').groupby(df['id-customer']) 2019-02-18T18:05:53.143Z+00:00 ... You should try to group by status and then get group Won and Not Won finally you could create a math equation to pull the ratio.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-divide-columns-in-pandas
How to divide columns in pandas - Quora
Answer (1 of 2): Given that the two columns-you want to perform division with, contains int or float type of values, you can do this using square brackets form, for example: [code]data_div = data['column_one']/data['column_two] [/code]Here data is the pandas data frame on which you want to perfo...