为什么df.apply(tuple)工作但不是df.apply(list)?

时间:2017-08-28 22:56:40

标签: python list pandas dataframe apply

这是一个数据框:

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

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

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

1 个答案:

答案 0 :(得分:5)

罪魁祸首是here。使用func=tuple可行,但使用func=list会在已编译的模块lib.reduce中引发异常:

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

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

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

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(以及其中一个pandas维护者commented the same),你最好使用列表理解:

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

通常apply会使用numpy ufunc或类似的。