我需要dtype在函数中使用pandas列,但由于某种原因,当我使用函数调用时apply,dtype更改为object.有谁知道这里发生了什么?
import pandas as pd
df = pd.DataFrame({'stringcol':['a'], 'floatcol': [1.5]})
df.dtypes
Out[1]:
floatcol float64
stringcol object
dtype: object
df.apply(lambda col: col.dtype)
Out[2]:
floatcol object
stringcol object
dtype: object
Run Code Online (Sandbox Code Playgroud)
请注意,如果直接传递列,则不会发生此问题:
f = lambda col: col.dtype
f(test.floatcol)
Out[3]: dtype('float64')
Run Code Online (Sandbox Code Playgroud)
Bre*_*arn 11
它似乎是由于优化DataFrame._apply_standard.该方法的代码中的"快速路径"创建一个输出Series,其dtype是dtype df.values,在您的情况下,object因为DataFrame是混合类型.如果你reduce=False转到你的apply来电,结果是正确的:
>>> df.apply(lambda col: col.dtype, reduce=False)
floatcol float64
stringcol object
dtype: object
Run Code Online (Sandbox Code Playgroud)
(我必须说,我不清楚这种reduce与文档相关的行为.)