![](/img/trans.png)
[英]Why AttributeError occurs in DataFrame.apply() but not in individual function call?
[英]Why and when does dataframe.apply give different results than using the function on an individual element?
我想将numpy.datetime64转换为datetime.date。 您能告诉我为什么方法2有效但方法1无效吗? 与调用fn(element)相比,dataframe.apply(fn)给出不同的结果是否很常见?
sample = np.datetime64('2018-03-31T00:00:00.000000000')
fails = pd.datetime.date(sample)
# TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a
# 'numpy.datetime64'
sample = np.datetime64('2018-03-31T00:00:00.000000000')
sample = pd.DataFrame([sample])
print(sample[0].apply(pd.datetime.date))
熊猫版本:“ 0.23.3”
numpy版本:“ 1.14.0”
问题不在apply函数中。
正如@miradulo在评论中解释的那样,DataFrame构造函数将datetime64值强制转换为Timestamp。 pd.datetime.date(pd.Timestamp(sample))可以正常工作,并且与方法2更具可比性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.