0

Let's say I want to convert a series of date strings to datetime using the following:

>>> import pandas as pd >>> dataframe.loc[:, 'DATE'] = pd.to_datetime(dataframe.loc[:, 'DATE']) 

Now, I see dataframe.loc[:, 'DATE'] as redundant. Is it possible in python that I call a function on an object and assign the return to the same object at the same time?

Something that looks like:

>>> pd.to_datetime(dataframe.loc[:,'DATE'], +) 

or

dataframe.loc[:,'DATE'] += pd.to_datetime() 

where + (or whatever) assigns the return of the function to its first argument

This question might be due to my lack of understanding on how programming languages are written/function, so please be gentle.

2 Answers 2

2

There is no such a thing. But you can achieve the same with:

name = 'DATE' dataframe[name] = pd.to_datetime(dataframe[name]) 

No need for .loc

Some methods support an inplace=True keyword argument. For example, sorting a dataframe gives you new one:

>>> df = pd.DataFrame({'DATE': [10, 7, 1, 2, 3]}) >>> df.sort_values() >>> df.sort_values('DATE') DATE 2 1 3 2 4 3 1 7 0 10 

The original remains unchanged:

>>> df DATE 0 10 1 7 2 1 3 2 4 3 

Setting inplace=True, modifies the original df:

>>> df.sort_values('DATE', inplace=True) >>> df DATE 2 1 3 2 4 3 1 7 0 10 
Sign up to request clarification or add additional context in comments.

2 Comments

@jezrael Thanks for the hint. Added an example.
sure, glad can help, explanation answers are hard for me, because poor English ;)
1

Closest Pandas gets to this is the ad-hoc "inplace" command that exists for a good portion of DataFrame functions.

For example, an inplace datetime operation happens to be hidden in the new set_index functionality.

df.set_index(df['Date'], inplace=True) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.