python - Conditional summing of columns in pandas -
i have following database in pandas:
student-id last-name first-name hw1 hw2 hw3 hw4 hw5 m1 m2 final 59118211 alf brian 96 90 88 93 96 78 60 59.0 59260567 anderson jill 73 83 96 80 84 80 52 42.5 59402923 archangel michael 99 80 60 94 98 41 56 0.0 59545279 astor john 93 88 97 100 55 53 53 88.9 59687635 attach zach 69 75 61 65 91 90 63 69.0
i want add columns have "hw" in them. suggestions on how can that?
note: number of columns containing hw may differ. can't reference them directly.
you df.filter(regex='hw')
return column names 'hw' , apply sum row-wise via sum(axis-1)
in [23]: df out[23]: studentid lastname firstname hw1 hw2 hw3 hw4 hw5 hw6 hw7 m1 0 59118211 alf brian 96 90 88 93 96 97 88 10 1 59260567 anderson jill 73 83 96 80 84 99 80 100 2 59402923 archangel michael 99 80 60 94 98 73 97 50 3 59545279 astor john 93 88 97 100 55 96 86 60 4 59687635 attach zach 69 75 61 65 91 89 82 55 5 59829991 bake jake 56 0 77 78 0 79 0 10 in [24]: df.filter(regex='hw').sum(axis=1) out[24]: 0 648 1 595 2 601 3 615 4 532 5 290 dtype: int64
Comments
Post a Comment