[python] pandas dataframe create new columns and fill with calculated values from same df

Here is a simplified example of my df:

ds = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
ds
      A         B         C         D
1  1.099679  0.042043  0.083903  0.410128
2  0.268205  0.718933  1.459374  0.758887
3  0.680566  0.538655  0.038236  1.169403

I would like to sum the data in the columns row wise:

ds['sum']=ds.sum(axis=1)
ds
      A         B         C         D       sum
1  0.095389  0.556978  1.646888  1.959295  4.258550
2  1.076190  2.668270  0.825116  1.477040  6.046616
3  0.245034  1.066285  0.967124  0.791606  3.070049

Now, here comes my question! I would like to create 4 new columns and calculate the percentage value from the total (sum) in every row. So first value in the first new column should be (0.095389/4.258550), first value in the second new column (0.556978/4.258550)...and so on... Help please

This question is related to python pandas calculated-columns

The answer is


In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to pandas

xlrd.biffh.XLRDError: Excel xlsx file; not supported Pandas Merging 101 How to increase image size of pandas.DataFrame.plot in jupyter notebook? Trying to merge 2 dataframes but get ValueError Python Pandas User Warning: Sorting because non-concatenation axis is not aligned How to show all of columns name on pandas dataframe? Pandas/Python: Set value of one column based on value in another column Python Pandas - Find difference between two data frames Pandas get the most frequent values of a column Python convert object to float

Examples related to calculated-columns

The condition has length > 1 and only the first element will be used pandas dataframe create new columns and fill with calculated values from same df getting "No column was specified for column 2 of 'd'" in sql server cte? Computed / calculated / virtual / derived columns in PostgreSQL SQL Server String Concatenation with Null