簡體   English   中英

這是熊貓的錯誤​​或功能嗎?

[英]Is this a pandas bug or feature?

如果滿足某些條件,我將嘗試用一個常數填充大熊貓系列。 作為簡化的測試用例,我將使用以下內容:

'-'*pd.Series([True]*5, dtype=bool)

結果是:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-0e3400ddc239> in <module>()
----> 1 '-'*pd.Series([True]*5, dtype=bool)

C:\Anaconda\lib\site-packages\pandas\core\ops.pyc in wrapper(left, right, name)
    529             if hasattr(lvalues, 'values'):
    530                 lvalues = lvalues.values
--> 531             return left._constructor(wrap_results(na_op(lvalues, rvalues)),
    532                                      index=left.index, name=left.name,
    533                                      dtype=dtype)

C:\Anaconda\lib\site-packages\pandas\core\ops.pyc in na_op(x, y)
    476                 result = np.empty(len(x), dtype=x.dtype)
    477                 mask = notnull(x)
--> 478                 result[mask] = op(x[mask], y)
    479             else:
    480                 raise TypeError("{typ} cannot perform the operation {op}".format(typ=type(x).__name__,op=str_rep))

TypeError: only integer arrays with one element can be converted to an index

但是,如果我執行以下操作:

'-'*pd.Series([True]*5, dtype=bool).astype(object)

我得到了預期的結果:

0    -
1    -
2    -
3    -
4    -
dtype: object

有人可以向我解釋發生了什么嗎? 我是否可能會選擇一種尷尬的方式?

我認為您正在選擇使用*運算符的尷尬方式。 使用pandas.Series.map會更容易嗎?

例如。

pd.Series([True]*5,dtype=bool).map( lambda x : '-' if x else None )

如果設置為使用*運算符,則請注意,您可以在兩個向量上使用它,而不是在標量+向量上使用:

my_filter = pd.Series([True]*5,dtype=bool)
pd.Series('-',index=my_filter.index) * my_filter

或者(如您dtype ,或多或少地確定了),如果您dtype調整dtype可以使用:

'-' * pd.Series([True]*5,dtype=object)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM