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
Discussions

Pandas - Creating new column with proportion/ratio from criteria/other cols
Similar to the other comment but I'd suggest just using a groupby apply to get a summary df.groupby('Surgeon').apply(lambda x: sum((x['Preop'] == 1) &(df['Conversion'] ==1))/sum((x['Preop'] == 1))).reset_index(name='Conversion Rate') More on reddit.com
๐ŸŒ r/learnpython
3
2
January 26, 2024
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
python - Calculating and creating percentage column from two columns - Stack Overflow
I have a df (Apple_farm) and need to calculate a percentage based off values found in two of the columns (Good_apples and Total_apples) and then add the resulting values to a new column within Appl... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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.
๐ŸŒ
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)

๐ŸŒ
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
Find elsewhere
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)
๐ŸŒ
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())
๐ŸŒ
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.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ divide-a-dataframe-in-a-ratio
Divide a DataFrame in a ratio
November 2, 2023 - Following example divides the dataframe in a ratio of 70% and 30% using the numpy.split() function. import pandas as pd import numpy as np dic = {"Letters":['A','B','C','D','E','F','G','H'], "Number":[1,2,3,4,5,6,7,8]} data = pd.DataFrame(dic) print("The Original data:") print(data) print("The ...
๐ŸŒ
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!
It only takes a couple lines of code. df['newColumnName'] = ratio_formula print(df[df['newColumnName'] == df['newColumnName'].max()]) ... This is my code: ###### This is the given code ####### import pandas as pd df = pd.read_csv("/usercode...
๐ŸŒ
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