简体   繁体   中英

Can i substract 2 column given some conditions pandas

I have a df that looks like this 一种

I want to subtract EndTime - StartTime only if channel is 1000 smth like this: df.loc[df['Channel'] == 1000]['X channel view time']=df['EndTime']-df['StartTime'] this should be the fastest but does not appear to be working so

def watch_time(row,channel):
    val=0
    if row['Channel']==channel:
        val=row['EndTime']-row['StartTime']   

    return val
df['BTV_view_time'] = df.apply(watch_time,args=250,axis=1)

but this is a lot slower?

You can do it for all rows then replace ones that don't fit your filter with 0 :

 df['X channel view time'] = df['EndTime'] - df['StartTime']
 df.loc[df['Channel'] == 1000, 'X channel view time'] = 0

You were not that far. Syntax is:

df.loc[df['Channel'] == 1000, 'X channel view time']=df.loc[df['Channel'] == 1000, 'EndTime']-df.loc[df['Channel'] == 1000, 'StartTime']

You could try something like this:

import numpy as np 
df['X channel view time'] = np.where(df['channel'] == 1000, df['EndTime'] - df['StartTime'], 0)

notice you are taking a slice of the df, that's why it is not working, you can do something like this:

smaller_df = df[df['Channel'] == 1000]['EndTime']-df[df['Channel'] == 1000]['StartTime']

you can also create a new column:

df['subtraction'] = [0]*len(df)
df['subtraction'] = df[df['Channel'] == 1000]['EndTime']-df[df['Channel'] == 1000]['StartTime']

replace [0]*len(df) by what you want if 'Channel' is different of 1000

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