Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13981

Setting Specific Column Totals in DataFrame dff to Desired Values

$
0
0

I'm trying to set specific column totals in DataFrame dff to certain predetermined values. Currently, I have a DataFrame dff constructed by performing various operations on multiple DataFrames (df, df2, df3, and df1) using multiplication and addition. After calculating the sum of rows and columns, I want to ensure that the column totals of dff are set to specific values, namely 6000, 7000, 8000, and 9000.

data = np.random.randint(100, 1000, size=(9, 4))df = pd.DataFrame(data, columns=['Q1', 'Q2', 'Q3', 'Q4'], index = ['A','B','C','D','E','F','G','H','I'])# Repeat the above for df1, df2, and df3# Define weightsweight_df = 0.1weight_df2 = 0.2weight_df3 = 0.3weight_df1 = 0.4# Calculate weighted sumdff = df.mul(weight_df).add(df2.mul(weight_df2)).add(df3.mul(weight_df3)).add(df1.mul(weight_df1))# Calculate sum of rowsdff['row_totals'] = dff.sum(axis=1)# Calculate sum of columnscolumn_totals = dff.sum(axis=0)new_rows = pd.DataFrame({'column_totals': column_totals}).Tdff = dff.append(new_rows)

How can I ensure that the column totals of DataFrame dff are set to specific values, such as 6000, 7000, 8000, and 9000, after performing the described operations on multiple DataFrames?

Adjust column_totals to match desired values

desired_column_totals = [616.9, 585.5, 682.4, 456.8] dff_adjusted = dff.copy() for col, val in zip(dff_adjusted.columns, desired_column_totals): dff_adjusted[col] += val - column_totals[col]

I've attempted to achieve this by adjusting the values in the column to match the desired total value. The code calculates the difference between the desired total value val and the current total value of the column column_totals[col], and then adds this difference to all the elements in the column. However this is not working. Is there a better way to do it using some inbuilt library. Any insights or alternative approaches would be appreciated.


Viewing all articles
Browse latest Browse all 13981

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>