简体   繁体   中英

How can I sum up 3 columns specifically using pandas for below data & create new column to flag if it's greater than 0 or equal to 0

For the below data I want to create columns, if the sum of A+B+C = 0 then I want to flag 'NoCommit' and if it is greater than 0 I want to flag 'Commit'

revno       author      msg                                        A    B   C

3030        rohit       modified                                   0    1   0
3031        rohit       Statistical Report changes Done            0    2   0
3032        sandeep     OTPIntegration flow changed                0    0   0
3033        sandeep     Captcha code Integration Done.             0    0   0

Use numpy.where with sum :

df['new'] = np.where(df[['A','B','C']].sum(axis=1).eq(0),'NoCommit','Commit')

Or:

df['new'] = np.where((df.A + df.B + df.C).eq(0),'NoCommit','Commit')

EDIT:

If columns are not numeric, use:

df['new'] = np.where(df[['A','B','C']].astype(float).sum(axis=1).eq(0),'NoCommit','Commit')

Naive Approach:

df = pd.DataFrame(data, columns=['A', 'B', 'C']
df['Commit'] = df['NoCommit'] = None
df.loc[:,['Commit', 'NoCommit']] = \
              [ (1,0) if i > 0 else (0,1) for i in df[['A','B','C']].sum(axis=1)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM