+-
python – 为什么df.apply(元组)工作但不是df.apply(list)?
这是一个数据帧:

    A  B  C
0   6  2 -5
1   2  5  2
2  10  3  1
3  -5  2  8
4   3  6  2

我可以使用df.apply检索一个基本上是原始df列的元组的列:

out = df.apply(tuple, 1)
print(out)

0    (6, 2, -5)
1     (2, 5, 2)
2    (10, 3, 1)
3    (-5, 2, 8)
4     (3, 6, 2)
dtype: object

但是,如果我想要一个值列表而不是它们的元组,我不能这样做,因为它没有给我我期望的东西:

out = df.apply(list, 1)
print(out)

    A  B  C
0   6  2 -5
1   2  5  2
2  10  3  1
3  -5  2  8
4   3  6  2

相反,我需要这样做:

out = pd.Series(df.values.tolist())
print(out)

0    [6, 2, -5]
1     [2, 5, 2]
2    [10, 3, 1]
3    [-5, 2, 8]
4     [3, 6, 2]
dtype: object

为什么我不能使用df.apply(list,1)来获得我想要的东西?

附录

一些可能的解决方法的时间安排:

df_test = pd.concat([df] * 10000, 0)

%timeit pd.Series(df.values.tolist()) # original workaround
10000 loops, best of 3: 161 µs per loop

%timeit df.apply(tuple, 1).apply(list, 1) # proposed by Alexander
1000 loops, best of 3: 615 µs per loop
最佳答案
罪魁祸首是 here.使用func = tuple它可以工作,但是使用func = list会在编译模块lib.reduce中引发异常:

ValueError: ('function does not reduce', 0)

正如您所看到的,他们捕获异常但不愿意处理它.

即使没有太宽泛的except子句,这也是熊猫中的一个错误.您可能会尝试在他们的跟踪器上提升它,但类似的问题已经关闭了一些不会修复或欺骗的味道.

16321: weird behavior using apply() creating list based on current columns

15628: Dataframe.apply does not always return a Series when reduce=True

后一个问题已经关闭,然后重新开放,并在几个月前转换为文档增强请求,现在似乎被用作任何相关问题的倾销场.

据推测,这不是一个高优先级,因为,作为piRSquared commented(以及其中一个熊猫维护者commented the same),你最好使用列表理解:

pd.Series([list(x) for x in df.itertuples(index=False)])

通常申请将使用numpy ufunc或类似.

点击查看更多相关文章

转载注明原文:python – 为什么df.apply(元组)工作但不是df.apply(list)? - 乐贴网