我需要从熊猫数据框中计算值,如下所示。
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)
答案 0 :(得分:2)
如果需要只对数字列应用解决方案,则对列进行过滤,然后按DataFrame.div
进行除法:
nan
如果所有列均为数字:
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