簡體   English   中英

用熊貓在一列中減去每兩行

[英]substract each two row in one column with pandas

我在google colab上執行下面的代碼時發現了這個問題,它可以正常工作

df['temps'] = df['temps'].view(int).div(1e9).diff().fillna(0).abs()
print(df)

但是在本地使用 jupyter notebook 時出現以下錯誤

ValueError                                Traceback (most recent call last)
Input In [13], in <cell line: 1>()
----> 1 df3['rebounds'] = pd.Series(df3['temps'].view(int).div(1e9).diff().fillna(0))

File C:\Python310\lib\site-packages\pandas\core\series.py:818, in Series.view(self, dtype)
    815 # self.array instead of self._values so we piggyback on PandasArray
    816 #  implementation
    817 res_values = self.array.view(dtype)
--> 818 res_ser = self._constructor(res_values, index=self.index)
    819 return res_ser.__finalize__(self, method="view")

File C:\Python310\lib\site-packages\pandas\core\series.py:442, in Series.__init__(self, data, index, dtype, name, copy, fastpath)
    440     index = default_index(len(data))
    441 elif is_list_like(data):
--> 442     com.require_length_match(data, index)
    444 # create/copy the manager
    445 if isinstance(data, (SingleBlockManager, SingleArrayManager)):

File C:\Python310\lib\site-packages\pandas\core\common.py:557, in require_length_match(data, index)
    553 """
    554 Check the length of data matches the length of the index.
    555 """
    556 if len(data) != len(index):
--> 557     raise ValueError(
    558         "Length of values "
    559         f"({len(data)}) "
    560         "does not match length of index "
    561         f"({len(index)})"
    562     )

ValueError: Length of values (830) does not match length of index (415)

任何解決此問題的建議!

這里有兩種方法可以讓它工作:

df3['rebounds'] = pd.Series(df3['temps'].view('int64').diff().fillna(0).div(1e9))

... 或者:

df3['rebounds'] = pd.Series(df3['temps'].astype('int64').diff().fillna(0).div(1e9))

對於以下示例輸入:

df3.dtypes:

temps    datetime64[ns]
dtype: object

df3:

       temps
0 2022-01-01
1 2022-01-02
2 2022-01-03

...上述兩個代碼示例都給出了以下輸出:

df3.dtypes:

temps       datetime64[ns]
rebounds           float64
dtype: object

df3:

       temps  rebounds
0 2022-01-01       0.0
1 2022-01-02   86400.0
2 2022-01-03   86400.0

問題可能在於view()本質上將現有系列的原始數據重新解釋為不同的數據類型。 為此,根據Series.view() 文檔(另請參見numpy.ndarray.view() 文檔),數據類型必須具有相同的字節數。 由於原始數據是datetime64 ,您將int指定為 view() 的參數的代碼可能不滿足此要求。 明確指定int64應該滿足它。 或者,使用astype()而不是view()和 int64 也可以。

至於為什么這在 colab 而不是 jupyter notebook 中有效,我不能說。 也許他們正在使用不同版本的 pandas 和 numpy,它們對int的處理方式不同。

我確實知道在我的環境中,如果我嘗試以下操作:

df3['rebounds'] = pd.Series(df3['temps'].astype('int').diff().fillna(0).div(1e9))

...然后我收到此錯誤:

TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32]

這表明int意味着int32 看看這是否適用於 colab 會很有趣。

暫無
暫無

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

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