gpt4 book ai didi

python - 为什么 astype timedelta64 不能在 ndarray 上工作?

转载 作者:行者123 更新时间:2023-11-30 22:19:50 26 4
gpt4 key购买 nike

为什么在以下示例中.astype('timedelta64[D]')无法转换ndarray

df = pd.DataFrame(pd.date_range('2017-01-01', periods=5, freq='W'), columns=['Val'])
df['Base'] = pd.datetime(2015, 1, 1)
df['Days'] = (df['Val'] - df['Base']).astype('timedelta64[D]') # Success
df['FailCast'] = (df['Val'].values - df['Base'].values).astype('timedelta64[D]') # Failure

print (df)

Val Base Days FailCast
0 2017-01-01 2015-01-01 731.0 731 days
1 2017-01-08 2015-01-01 738.0 738 days
2 2017-01-15 2015-01-01 745.0 745 days
3 2017-01-22 2015-01-01 752.0 752 days
4 2017-01-29 2015-01-01 759.0 759 days

特别考虑到在事后作为单独的操作应用时它将成功地转换值:例如,

df['FailCast'] = df['FailCast'].astype('timedelta64[D]') # Success!

最佳答案

请注意,这些是等效的:

df['FailCast'] = df['FailCast'].values.astype('timedelta64[D]')

还有

df['FailCast'] = np.array([731, 738, 745, 752, 759], dtype='timedelta64[D]')

在获得相同的输出后传递.astype(int)

关于python - 为什么 astype timedelta64 不能在 ndarray 上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978697/

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