[英]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.我正在尝试将pandas.core.series.Series
分配给 pandas dataframe 列。
First I create a function:首先我创建一个 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:然后我将它应用于 pandas df 并将其定义为pd_object
,它返回一个pandas.core.series.Series
类型,其中包含set_date()
Z78E6221F6393D1356Z:DB398F14CED6
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.然后,当我将它分配给一个新的 col df['month']=pd_object
时,它返回给我一个 pandas dataframe 列,其中满是None
行,当预期结果必须是set_date()
Z78E6221F6393D14CEDZF8 这些行时。
How could I assign pd_object
to a new pandas dataframe column?如何将pd_object
分配给新的 pandas dataframe 列?
Your set_date
function only prints, yet does not return anything, ie None
.您的set_date
function 仅打印,但不返回任何内容,即None
。 That's why you get all the None
.这就是为什么你得到所有的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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.