我需要在函数中使用pandas列的dtype
,但由于某些原因,当我使用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
请注意,如果直接传递列,则不会发生此问题:
f = lambda col: col.dtype
f(test.floatcol)
Out[3]: dtype('float64')
答案 0 :(得分:11)
这似乎是由于DataFrame._apply_standard
的优化。 "快速路径"在该方法的代码中创建一个输出Series,其dtype是df.values
的dtype,在您的情况下为object
,因为DataFrame是混合类型。如果您将reduce=False
传递给apply
来电,结果是正确的:
>>> df.apply(lambda col: col.dtype, reduce=False)
floatcol float64
stringcol object
dtype: object
(我必须说,我不清楚reduce
的这种行为与文档的关系如何。)
答案 1 :(得分:0)
对于熊猫版本v0.23+
,答案是:
>>> df.apply(lambda x: x.dtype, result_type='expand')
即使Pandas文档声称result_type
参数“仅在axis=1
(列)时起作用”,此方法仍然有效
信用@jezrael