user11953618
user11953618

Reputation: 69

Multiplying the values in one columns by values in other columns by ignoring zero in pandas without hard cording it?

I want to multiply values in a columns by values in other columns. I normally multiply the values using by specifying the column using following formula in pandas e.g. dataframe.column1 * dataframe.column2.

Here is the example DataFrame:

enter image description here

I want to multiply values as follows:

(continue to other columns such as DEF_POINT3, DEF_POINT4 etc..) each of the above columns have nan values, which I do not want to multiply with values in PRO_RATE columns.

Expected Result:

enter image description here

Sample DataFrame:

data = {'PRO_RATE':[.5,.3,.6,.7],
        'DEF_POINT1':[1,7,8,9],
        'DEF_POINT2':[np.nan,2,3,4],
        'DEF_POINT3':[np.nan,np.nan,10,15],
        'DEF_POINT4':[np.nan,np.nan,np.nan,20]}
df = pd.DataFrame(data)

Since I am new to pandas and python I do not know how to write a function/Loop to perform above task without hard coding it? Please help...

Upvotes: 0

Views: 253

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62413

Given the DataFrame provided in the question:

for column in df.columns[2:]:
    isnull_count = (df[column].isnull().sum())
    calc_values = df.PRO_RATE * df[x].shift(-isnull_count)
    calc_values = calc_values.dropna().tolist()  # optional line
    calc_values = [round(x, 2) for x in calc_values]  # optional line
    print(f'{x}: {calc_values}')

Output:

DEF_POINT2: [1.0, 0.9, 2.4]
DEF_POINT3: [5.0, 4.5]
DEF_POINT4: [10.0]

Upvotes: 1

Related Questions