報錯信息
ValueError: Wrong number of items passed 13, placement implies 1
解決方案
首先需要判明pandas的版本是什么,不同的版本擁有不同的解決方案,或者直接去看本地pandas源碼中的對於參數的解釋也可以。因為在最開始的時候,我直接去百度搜索pandas apply
,其實前面幾個都是舊版本的,根據舊版本的可能會出現錯誤。
apply中有一個參數是reduce
,文檔如下。它的作用就是,當DataFrame為空的時候,使用reduce來確定返回的類型。
1. None 默認,讓pandas直接去猜
2. True,總是返回Series
3. False,總時返回DataFrame
注意:在0.23.0版本后,要需要讓result_type='reduce'
才能生效。(所以我說要看不同版本各自的文檔)
reduce : bool or None, default None
Try to apply reduction procedures. If the DataFrame is empty,
`apply` will use `reduce` to determine whether the result
should be a Series or a DataFrame. If ``reduce=None`` (the
default), `apply`'s return value will be guessed by calling
`func` on an empty Series
(note: while guessing, exceptions raised by `func` will be
ignored).
If ``reduce=True`` a Series will always be returned, and if
``reduce=False`` a DataFrame will always be returned.
.. deprecated:: 0.23.0
This argument will be removed in a future version, replaced
by ``result_type='reduce'``.
實例
對於第一種,如果把他當作一列就肯定會報錯了。
更新
在更加新的版本中直接使用result='reduce'
即可
result_type : {'expand', 'reduce', 'broadcast', None}, default None
These only act when ``axis=1`` (columns):
* 'expand' : list-like results will be turned into columns.
* 'reduce' : returns a Series if possible rather than expanding
list-like results. This is the opposite of 'expand'.
* 'broadcast' : results will be broadcast to the original shape
of the DataFrame, the original index and columns will be
retained.
The default behaviour (None) depends on the return value of the
applied function: list-like results will be returned as a Series
of those. However if the apply function returns a Series these
are expanded to columns.
.. versionadded:: 0.23.0