我在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)
任何解決此問題的建議!
uj5u.com熱心網友回復:
這里有兩種方法可以讓它作業:
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應該滿足它。或者,使用int64astype()代替view()也可以。
至于為什么這在 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 會很有趣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474727.html
標籤:Python 熊猫 约会时间 机器学习 jupyter-笔记本
