gpt4 book ai didi

python - 有条件地替换日期时间 - python

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

我在数据框中有一个“发布日期”列,格式为 '2017-03-01' .类型是 <datetime64>[ns] .我想把'2017-03-31'之后的值改成'2017-03-31',其他都保持不变。

当我输入 df['Posting Date']>'2017-03-31' 时,它可以正确地向我显示满足条件的所有行。所以我猜日期过滤功能起作用了。

但是,当我使用 numpy.where把条件写成这样:

df['Posting Date'] = np.where(df['Posting Date']>'2017-03-31','2017-03-31,'df['Posting Date'])

它会引发 invalid type promotion错误。

我也试过df.loc并且发生相同的错误。

df.loc[df['Posting Date']>'2017-03-31','Posting Date']='2017-03-31'

ValueError: invalid literal for int() with base 10: '2017-03-31'

我想知道为什么会出现错误。如何正确替换日期?任何有效的方法都可以。

最佳答案

这是因为正在尝试用 datetime dtype 列中的字符串替换 datetime,所以在 np.where 中传递一个日期时间,即

df['Posting Date'] = np.where(df['Posting Date']>'2017-03-31',pd.to_datetime(['2017-03-31']),df['Posting Date'])

示例输出:

df = pd.DataFrame({'Posting Date': pd.to_datetime(['20-4-2017','20-4-2017','20-4-2017','20-3-2017','20-2-2017'])})
df['Posting Date'] = np.where(df['Posting Date']>'2017-03-31',pd.to_datetime(['2017-03-31']),df['Posting Date'])

输出:

Posting Date0   2017-03-311   2017-03-312   2017-03-313   2017-03-204   2017-02-20

Better one posted by @pirSquared in comment using clip i.e

df['Posting Date'] = df['Posting Date'].clip(upper=pd.Timestamp('2017-03-31')) 

关于python - 有条件地替换日期时间 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46751078/

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