I am working with data frame. One of the columns contains date where the format of cell are mixed between date, time and string. The sample date frame is as follow:
JavaScript
x
4
1
df = pd.DataFrame()
2
df['Date'] = ['EPL','Sunday 21st April 2019','13:30:00','13:30:00','French Ligue 1','14:30:00']
3
df['Name'] = ['A','B','C','D','E','F']
4
I want to create a new column that contains the text of date column. The expected output is as follows:
How can I do that?
Advertisement
Answer
IIUC using to_datetime
, the select the position return NaN, then ffill
JavaScript
1
12
12
1
df.loc[pd.to_datetime(df.Date,errors='coerce').isnull(),'col']=df.Date
2
df.col=df.col.ffill()
3
df
4
Out[867]:
5
Date Name col
6
0 EPL A EPL
7
1 Sunday 21st April 2019 B EPL
8
2 13:30:00 C EPL
9
3 13:30:00 D EPL
10
4 French Ligue 1 E French Ligue 1
11
5 14:30:00 F French Ligue 1
12