noob
noob

Reputation: 3811

Convert to datetime using column position/number in python pandas

Very simple query but did not find the answer on google.

df with timestamp in date column

Date 
22/11/2019 22:30:10 etc. say which is of the form object on doing df.dtype()

Code:

df['Date']=pd.to_datetime(df['Date']).dt.date 

Now I want the date to be converted to datetime using column number rather than column name. Column number in this case will be 0(I have very big column names and similar multipe files, so I want to change date column to datetime using its position '0' in this case).

Can anyone help?

Upvotes: 1

Views: 50

Answers (1)

jezrael
jezrael

Reputation: 863256

Use DataFrame.iloc for column (Series) by position:

df.iloc[:, 0] = pd.to_datetime(df.iloc[:, 0]).dt.date 

Or is also possible extract column name by indexing:

df[df.columns[0]] = pd.to_datetime(df[df.columns[0]]).dt.date 

Upvotes: 1

Related Questions