aloha dev
aloha dev

Reputation: 29

How to get the value from data frame?

I need to calculate the value from panda data frame as below.

W1 (-1.626224/-1.003328) (0.251927/-1.003328) (0.370969/-1.003328)

W2 ...

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5,3),columns=['S1','S2','S3'],index = ['W1','W2','W3','W4','W5'])
print (df)

input
          S1        S2        S3
W1 -1.626224  0.251927  0.370969
W2 -1.290303  0.789866  1.822245
W3 -1.140703 -1.460939  0.398063
W4 -0.160597 -1.111473  1.750486
W5 -0.590757  0.523236  0.952986

rowsum = df.select_dtypes(pd.np.number).sum(axis=1)
print (rowsum)

Upvotes: 2

Views: 38

Answers (1)

jezrael
jezrael

Reputation: 863166

If need apply solution only for numeric columns filter columns first and then dividy by DataFrame.div:

c = df.select_dtypes(pd.np.number).columns
df[c] = df[c].div(df[c].sum(axis=1), 0)
print (df)
          S1        S2        S3
W1  0.338192 -0.250081  0.070064
W2  0.268333 -0.784077  0.344161
W3  0.237222  1.450232  0.075181
W4  0.033398  1.103327  0.330608
W5  0.122855 -0.519401  0.179987

If all columns are numeric:

df = df.div(df.sum(axis=1), 0)

Upvotes: 2

Related Questions