Concatenating many time and date columns

2024/11/16 10:36:02

I have many date and time column pairs (around 15 each) that share the same prefix, ie. SH or DEL. The columns are all of dtype object, ie. string. All the columns belong to the same Dataframe. Here is an example of two such pairs:

  SH_DATE         DEL_DATE          SH_TIME      DEL_TIME                2020-04-22      2020-04-27         19:42:00     19:11:00           2020-04-22      2020-04-25         19:42:00     19:26:00           2020-04-24      2020-04-24         09:55:00     09:55:00           2020-04-24      2020-04-26         14:27:00     14:27:00           

I'd like to combine each date/time column pair into a single column. My first inclination was to utilize LIKE statements for time and date columns in the dataframe, by extracting date/time in their own distinct lists, and then looping over them for the pd.concat function, but haven't found a solution yet.

Example of desired output:

     SH_DATETIME            DEL_DATETIME                        2020-04-22 19:42:00     2020-04-27 19:11:00                2020-04-22 19:42:00     2020-04-25 19:26:00                    2020-04-24 09:55:00     2020-04-24 09:55:00                    2020-04-24 14:27:00     2020-04-26 14:27:00          
Answer

Determine the unique column name prefixes (e.g. 'SH' or 'DEL') and combine the respective date / time columns with a space as separator. Parse the combined to datetime.

pfxs = df.columns.to_series().str.replace('_TIME', '').str.replace('_DATE', '').unique()for p in pfxs:if f'{p}_DATE' in df.columns and f'{p}_TIME' in df.columns:df[f'{p}_DATETIME'] = pd.to_datetime(df[f'{p}_DATE']+' '+df[f'{p}_TIME'])
dfSH_DATE    DEL_DATE  ...         SH_DATETIME        DEL_DATETIME
0  2020-04-22  2020-04-27  ... 2020-04-22 19:42:00 2020-04-27 19:11:00
1  2020-04-22  2020-04-25  ... 2020-04-22 19:42:00 2020-04-25 19:26:00
2  2020-04-24  2020-04-24  ... 2020-04-24 09:55:00 2020-04-24 09:55:00
3  2020-04-24  2020-04-26  ... 2020-04-24 14:27:00 2020-04-26 14:27:00

To make this somewhat fail-safe, you can add checks to make sure a date and a time column exists for given prefix before attempting to combine.

In case some elements in your date & time columns cannot be parsed to datetime, setting errors='coerce' might be an option, leaving you with NaT for elements that fail to parse, e.g.

pd.to_datetime(df[f'{p}_DATE']+' '+df[f'{p}_TIME'], errors='coerce')

in the code above.

https://en.xdnf.cn/q/119536.html

Related Q&A

Python with ICS files and CSV [duplicate]

This question already has answers here:Parsing files (ics/ icalendar) using Python(6 answers)Closed 5 years ago.one friend ask me some help on a personnal project, but I have to admit my skills in Pyth…

loading my data in numpy genfromtxt get errors

I have my data file contain 7500 lines with :Y1C 1.53 -0.06 0.58 0.52 0.42 0.16 0.79 -0.6 -0.3 -0.78 -0.14 0.38 0.34 0.23 0.26 -1.8 -0.1 -0.17 0.3…

Install dlib with cuda support ubuntu 18.04

I have CUDA 9.0 and CUDNN 7.1 installed on Ubuntu 18.04(Linux mint 19). Tensorflow-gpu works fine on GPU(GTX 1080ti).Now i am trying to build dlib with CUDA support:sudo python3 setup.py install --yes …

View 3 dimensional Numpy array in Matplotlib and taking arguments from Keyboard or mouse

I have 3 dimensional data say (5,100,100). Now I would like to see them slice by slice upon hitting the down arrow button.

python default argument syntax error

I just wrote a small text class in python for a game written using pygame and for some reason my default arguments arent working. I tried looking at the python documentation to see if that might give m…

Variable not defined (Python)

FlightType=input("Which flight would you like to fly? Type 2 Seater, 4 Seater, or Historic.") # No validation included for the inputFlightLen=input("Would you like to book the 30 minu…

PyGame: draw.rect() has invalid parameters

Im trying to learn mouse events with PyGame, and Im trying to draw a box wherever the user clicks. Im setting a variable equal to pygame.mouse.get_pos(), and calling individual tuple members according …

Cant press enter in selenium2library

Im trying to make a test that will open Facebook, log in and search something. However Im having trouble getting Facebook to search. Selenium types whatever it needs in the search bar, but I cant find …

Converting string to datetime in Python using strptime

Im trying to convert the following String to datetime object in Python.datetime_object = datetime.strptime(Sat, 26 Nov 2016 15:17:00 +0000, %a, %b %d %Y %H:%c %z)I get the following error,File "&l…

Is there any differences between python2 and python3 about adding menu bar to Frame in tkinter?

Im trying to porting a project 2to3 on python, and stuck in tkinter.In python2, there is no problem with adding menu bar to Frame in tkinter,but python3 occured attribute error. (Frame object has no at…