简体   繁体   中英

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?

Your set_date function only prints, yet does not return anything, ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM