gpt4 book ai didi

python - 如何在 Pandas 0.24.2 中将 offsets.MonthEnd 系列转换为 int

转载 作者:行者123 更新时间:2023-11-28 18:57:58 25 4
gpt4 key购买 nike

我计算 pd.Period 类型的两列之间的增量。在 0.24 之前,它将返回一个 int 类型,但在 0.24 中不再返回,它将返回类似一系列的 1 * MonthEnds,2 * MonthEnds,...我想将其转换为 int 类型。

我可以使用 apply 来实现,例如,

df.apply(lambda x: x['z'].n)

((df['x'] - df['y']) / np.timedelta64(1, 'M')).round()

但我想知道是否还有其他解决方法。

df = pd.DataFrame({'x':pd.date_range(start='2001-01-01', periods=10), 'y':pd.date_range(start='2002-01-01', periods=10)})

在Pandas 0.24之前,下面的代码会返回一个int类型的列

df['z'] = df['x'].dt.to_period('M') - df['y'].dt.to_period('M')

但是0.24改变了返回类型,如上所述有两种方法仍然返回一个int列,但我想知道是否有其他方法可以实现这一点。

最佳答案

使用 astype 将返回一个 int 而不是 DateOffset 对象:

df['x'].dt.to_period('M').astype(int) - df['y'].dt.to_period('M').astype(int)

0 -12
1 -12
2 -12
3 -12
4 -12
5 -12
6 -12
7 -12
8 -12
9 -12
dtype: int64

关于python - 如何在 Pandas 0.24.2 中将 offsets.MonthEnd 系列转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978907/

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