divide value in table by another value in table based on column value in python

You can use pandas package in Python to divide the values in one column of a DataFrame by values in another column, based on a selected condition. Here's an example:

main.py
import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'A': [10, 20, 30, 40],
                   'B': [2, 4, 0, 5],
                   'C': ['yes', 'yes', 'no', 'yes']})

# divide values in column A by values in column B, where values in column C = 'yes'
df.loc[df['C'] == 'yes', 'A'] = df.loc[df['C'] == 'yes', 'A'] / df.loc[df['C'] == 'yes', 'B']

# print the updated DataFrame
print(df)
403 chars
13 lines

In the above code, we first create a sample DataFrame df with three columns A, B, and C. Then we use the .loc method to select only the rows where values in column C is equal to 'yes'. We use the .loc method again to select only the values in column A and B for those rows. We then divide the values in column A by the values in column B, using the / operator. Finally, we update the only the selected rows and column A in the original DataFrame df with the new calculated values.

The resulting output should look like this:

main.py
      A  B    C
0   5.00  2  yes
1  20.00  4  yes
2  30.00  0   no
3   8.00  5  yes
84 chars
6 lines

Note that we only updated column A for the selected rows where column C is equal to 'yes'. The other rows remain the same.

gistlibby LogSnag