gpt4 book ai didi

python - 如何使用 pandas.diff 区分 int64

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:55 25 4
gpt4 key购买 nike

>>> pd.DataFrame([3,4,5], dtype='int64').diff()
0
0 NaN
1 1.0
2 1.0

我希望不要转换数据类型两次,这可能吗?

最佳答案

是的,如果您需要,您可以使用 np.diff -

numpy.diff(a, n=1, axis=-1)

Calculate the n-th discrete difference along given axis.

The first difference is given by out[n] = a[n+1] - a[n] along the given axis, higher differences are calculated by using diff recursively.

>>> df
A B
0 1 4
1 2 5
2 3 6

>>> np.diff(df.values, axis=0)
array([[1, 1],
[1, 1]])

# or as in your example:
>>> np.diff(pd.DataFrame([3,4,5], dtype='int64')[0])
array([1, 1], dtype=int64)

请注意,如果不引入 NaN,则无法将其分配回原始数据帧,并且 NaN 是 float 类型,这意味着您的结果将自动强制为 float 。

关于python - 如何使用 pandas.diff 区分 int64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47564363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com