我需要在一个函数中使用 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')
DataFrame.to_sql
存在类似的 bug... 我想知道这种“优化”作为默认行为是否有问题,因为我使用的每个 dataframe 几乎都有混合数据类型... - maxymooTypeError: <lambda>() got an unexpected keyword argument 'reduce'
。 - Rishabh Agrahariapply
已经更改了,现在它有一个result_type
参数,而不是reduce
。但是它似乎也被更改了,所以问题所问的问题不再存在(即,仅使用常规apply不再强制将列转换为对象dtype)。 - BrenBarn