【发布时间】:2021-06-06 01:43:05
【问题描述】:
问题描述
当提供一个返回不同 dtype 的数值列表的 func 时,DataFrame 的 apply 会将所有返回的值向上转换为一个通用类型。例如,在下面的代码中,第 2 列中的元素,整数“3”,由 apply() 转换为复数 (3.0+0.0j)。
df = pd.DataFrame([1,2,3])
df.apply(lambda row: [ 1+5j, 3], axis='columns', result_type='expand')
0 1
0 1.0+5.0j 3.0+0.0j
1 1.0+5.0j 3.0+0.0j
2 1.0+5.0j 3.0+0.0j
此行为继承自Numpy's type determination:
If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.
有没有办法为DataFrame的apply提供dtype参数?
预期产出 0 1
0 1.0+5.0j 3
1 1.0+5.0j 3
2 1.0+5.0j 3
【问题讨论】:
-
看起来是
expand选项正在执行此操作。没有它,结果是 1 列包含列表元素。