简体   繁体   中英

Passing values to new columns based on string in one column in a Pandas Dataframe

I have a fairly basic script which pulls some data from a web page (which I have no control over) and passes the data to a dataframe. The output I have looks like this currently:

             language    open-days    open-time   close-time     dept
0             English        24/7                               Sales
1             Spanish       Mo-Fr        07:00        17:00     Sales
2             Spanish       Sa-Su        08:00        15:00     Sales

What I'd like to do is:

1) Have two new columns per day of the week 2) Check the open-days column and see when the line is open (if it's 24/7 pass 0) 3) Pass the open and close time to new columns

The output I'm envisioning here is like so:

             language    open-days    open-time   close-time     dept     mon-open     mon-closed
0             English        24/7                               Sales            0      0
1             Spanish       Mo-Fr        07:00        17:00     Sales        07:00      17:00
2             Spanish       Sa-Su        08:00        15:00     Sales        08:00      15:00

So far all I've managed to do is somehow ruin my current dataframe or come up with a load of empty columns appended to the right.

Say that your original dataframe is called df . Then you need to add the two columns as follows

df['mon-open'] = ((df['open-days']!='24/7').astype(int) * df['open-time']).replace('':'0')
df['mon-closed'] = ((df['open-days']!='24/7').astype(int) * df['close-time']).replace('':'0')

EDIT If you need a new pair of columns for each entry in open-days then you need to modify the condition df['open-days']!='24/7' to pick up your required entry (say Mon-Fri )

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