用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:Python310libsite-packagespandascoreseries.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:Python310libsite-packagespandascoreseries.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:Python310libsite-packagespandascorecommon.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应该满足它。或者,在int64中使用astype()而不是view()也可以工作。

至于为什么这工作在colab而不是在jupyter笔记本,我不能说。也许他们使用的是不同版本的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上是否有效将会很有趣。

最新更新