Sum Specific Columns Among Rows

summing rows of specific columns then dividing by the sum

Try this way to specify the column (by sub-setting Df), and then indicating the margin as 1

Df_new = t(apply(Df[,c(1:3)], 1, \(x) x/sum(x)))

lose draw win
[1,] 0.5000 0.1428571 0.3571429
[2,] 0.0625 0.1250000 0.8125000

sum cells of certain columns for each row

You could do something like this:

summed <- rowSums(zscore[, c(1, 2, 3, 5)])

SUM specific column values that have integers where row meets a condition and place in new row

you can use rolling window to calculate the sum of pair of two columns, then concat the result

col=[1,0,1,0]
df2=pd.concat([df,
df.loc[df['ID'].isin(['AA','BB']) ]
.rolling(2, axis=1).sum() # calc rolling windows sum of two columns
.shift(-1, axis=1) # shift result to left
.fillna(0) # fill null values
.mul(col) # multipley to keep sum in alternate columns
]
)
df2.sort_index(axis=0, inplace=True)

#create a column with a new ID
df2['ID2']=df2['ID']+'_New'

# fill NA values with the row above
df2['ID2'].fillna(method='ffill', inplace=True)

#reset index
df2=df2.reset_index()

# where the ID is null (our new summed row), assign the ID2 to ID
df2.loc[df2['ID'].isna(), 'ID'] = df2['ID2']

#drop unwanted columns
df2.drop(columns=['ID2', 'index'], inplace=True)
df2

    ID      Q121    Q221    Q321    Q421
0 AA 8.0 4.8 3.1 5.3
1 AA_New 12.8 0.0 8.4 0.0
2 BB 0.6 0.7 0.3 0.9
3 BB_New 1.3 0.0 1.2 0.0```



Related Topics



Leave a reply



Submit