【问题标题】:Providing dtypes for Dataframe.apply()为 Dataframe.apply() 提供数据类型
【发布时间】: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 列包含列表元素。

标签: python pandas numpy


【解决方案1】:

虽然可以在 numpy 数组中指定混合 dtype,但似乎必须将项目定义为 tuple

np.array((1+5j, 3), dtype='|complex, int')

因此潜在的解决方案包括:

  1. 使用.astype({1: 'int'})

  2. 拆分实数/虚数,然后根据需要重新组合它们:

df = df.apply(lambda row: [i for x in [ 1+5j, 3] for i in [x.real, x.imag]], axis='columns', result_type='expand')
df = df[df.columns[df.sum(axis=0)!=0]]

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 1970-01-01
    • 2021-12-01
    • 2019-01-22
    • 2021-12-08
    • 2012-02-08
    • 2013-07-25
    • 2013-09-11
    • 1970-01-01
    相关资源
    最近更新 更多