-2

Below is the code i am trying to use in python, have tried everything.Can anyone please help ..

import pandas as pd
# Using DataFrame.astype() function
df["Date"] = df["Date"].astype('datetime64[ns]')
print (df.dtypes)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[24], line 3
      1 import pandas as pd
      2 # Using DataFrame.astype() function
----> 3 df["Date"] = df["Date"].astype('datetime64[ns]')
      4 print (df.dtypes)

NameError: name 'df' is not defined

I had tried to import library and other google solution but not solved.

2

1 Answer 1

-1

You never define the DataFrame df through df = pd.DataFrame(). Try

import pandas as pd

# Define df
df = pd.DataFrame(columns=["Date"])

# Using DataFrame.astype() function
df["Date"] = df["Date"].astype('datetime64[ns]')
print(df.dtypes)
Sign up to request clarification or add additional context in comments.

3 Comments

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\indexes\base.py:3804, in Index.get_loc(self, key, method, tolerance) 3802 return self._engine.get_loc(casted_key) 3803 except KeyError as err: -> 3804 raise KeyError(key) from err 3805 except TypeError: 3806 # If we have a listlike key, _check_indexing_error will raise 3807 # InvalidIndexError. Otherwise we fall through and re-raise 3808 # the TypeError. 3809 self._check_indexing_error(key) KeyError: 'Date'
you suggestion works very well but again stuck at above error
@aryan I've adjusted my solution accordingly. It now creates a DataFrame with an empty "Date" column first and then changes the datatype of it to "datetime64[ns]". Hope this helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.