AlSub
AlSub

Reputation: 1155

how to assign a pandas.core.series.Series to a pandas dataframe column

I am trying to assing a pandas.core.series.Series to a pandas dataframe column.

First I create a function:

####################################### set month #################################
import datetime
import pandas as pd

actual_date = datetime.now()
actual_date = datetime.strptime("{}/{}/{}".format('01', actual_date.month, actual_date.year), "%d/%m/%Y")

def set_date(actual_date):
    result = actual_date - dateutil.relativedelta.relativedelta(months=1)
    print(datetime.strftime(result, "%d/%m/%Y"))

Then I apply it over a pandas df an define this as pd_object which returns a pandas.core.series.Series type which contains set_date() output:

pd_object = pd.Series(df.apply(lambda x: set_date(actual_date), axis=1));

Then when I assign it to a new col df['month']=pd_object it returns me a pandas dataframe column full of None rows, when the expected result has to be set_date() output over these rows.

How could I assign pd_object to a new pandas dataframe column?

Upvotes: 0

Views: 305

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150765

Your set_date function only prints, yet does not return anything, i.e. None. That's why you get all the None. Maybe you mean:

def set_date(actual_date):
    result = actual_date - dateutil.relativedelta.relativedelta(months=1)
    return datetime.strftime(result, "%d/%m/%Y")

# your `apply` code seems to return a single, constant value for the whole dataframe
# you can just let Pandas broadcast that to the whole data
df['month'] = set_date(actual_date)

Upvotes: 1

Related Questions