我在数据框中有一个“发布日期”列,格式为'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'
我想知道为什么会发生错误。如何正确更换日期?无论哪种方法都有效。
答案 0 :(得分:1)
因为它试图用datetime dtype列中的字符串替换datetime,所以在np.where中传递一个datetime,即
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 Date 0 2017-03-31 1 2017-03-31 2 2017-03-31 3 2017-03-20 4 2017-02-20
@pirSquared在评论中使用剪辑
发表了更好的评论df['Posting Date'] = df['Posting Date'].clip(upper=pd.Timestamp('2017-03-31'))