EGM8686
EGM8686

Reputation: 1572

Python - Pandas: Split-Divide DataFrame with two Totals

I have a DataFrame that has two totals like this:

v1  v2  x1  x2  t1  t2
5   5   8   3   10  11 
4   9   2   1   13   3 
10  10  8   3   20  11 

How can I convert it something like this

v1   v2   x1   x2  t1  t2
50%  50%  72%  28% 10  11
30%  70%  66%  33% 13   3
50%  50%  72%  28% 20  11

No rounding is needed.Totals T1 and T2 can either remain or be deleted

Cheers!

Upvotes: 0

Views: 49

Answers (3)

BernardL
BernardL

Reputation: 5434

You can manually divide the columns that suit your needs, for example:

df['v1'] = (df['v1'] / df['t1']) * 100

Upvotes: -1

jezrael
jezrael

Reputation: 862581

Use filter with div for division and join together by concat:

df = pd.concat([df.filter(like='v').div(df['t1'], axis=0),
                df.filter(like='x').div(df['t2'], axis=0)], axis=1)
print (df)
         v1        v2        x1        x2
0  0.500000  0.500000  0.727273  0.272727
1  0.307692  0.692308  0.666667  0.333333
2  0.500000  0.500000  0.727273  0.272727

If want also total columns:

df = pd.concat([df.filter(like='v').div(df['t1'], axis=0),
                df.filter(like='x').div(df['t2'], axis=0),
                df[['t1','t2']]], axis=1)
print (df)
         v1        v2        x1        x2  t1  t2
0  0.500000  0.500000  0.727273  0.272727  10  11
1  0.307692  0.692308  0.666667  0.333333  13   3
2  0.500000  0.500000  0.727273  0.272727  20  11

Upvotes: 0

user3483203
user3483203

Reputation: 51165

You can use basic division:

a = df.iloc[:, :4].values
b = np.repeat(df.iloc[:, 4:].values, 2, axis=1)

pd.DataFrame(a / b, columns=df.columns[:4])

    v1        v2        x1        x2
0  0.500000  0.500000  0.727273  0.272727
1  0.307692  0.692308  0.666667  0.333333
2  0.500000  0.500000  0.727273  0.272727

Upvotes: 2

Related Questions