简体   繁体   English

删除 pandas 中 dataframe 的日期时间列中具有特定日期的行

[英]deleting rows having a particular date in the datetime column of dataframe in pandas

I have to remove the rows having date "2019-10-07" in the first column date.我必须删除第一列日期中日期为“2019-10-07”的行。

I have created a date1 column that extracts the exact date from first column and then apply the code,我创建了一个date1列,它从第一列中提取确切的日期,然后应用代码,

df2 = df2[df2['date1'] != '2019-10-07']. 

I have to create this date1 column because it was mentioned in the problem.我必须创建这个date1列,因为它在问题中被提及。 the link to the data frame is as follows:数据框的链接如下:

https://drive.google.com/file/d/1vTKoaQ2rtpup5gPXjmQIavG5v4owNRvk/view?usp=sharing https://drive.google.com/file/d/1vTKoaQ2rtpup5gPXjmQIavG5v4owNRvk/view?usp=sharing

 import pandas as pd
 import numpy as np
 df2=pd.read_csv('TCS.csv').sort_values(by='Date') 
 date1 = pd.to_datetime(df2['Date'], format='%Y/%m/%d,%H:%M:%S', 
 errors='coerce') #few rows were having a diff date format
 date2 = pd.to_datetime(df2.loc[date1.isna(), 'Date'], format='%d-%m- 
 %Y,%H:%M:%S')
 df2['Date'] = date1.fillna(date2)                    
 df2['date1'] = pd.to_datetime(df2['Date'], format= '%Y/%m/%d').dt.date             
 df2['time1'] = pd.to_datetime(df2['Date'], format= '%Y/%m/%d').dt.time

 df2 = df2[df2['date1'] != '2019-10-07']

The code编码

df2 = df2[df2['date1'] == '2019-10-07'] 

is working when applying it seperately with the new dataframe.与新的 dataframe 单独应用时正在工作。 but not in this code但不在此代码中

You're checking for equality against a string even though your values are of type datetime.date.即使您的值是 datetime.date 类型,您也正在检查字符串是否相等。 Try the following:尝试以下操作:

df2[df2['date1'] != pd.to_datetime('2019-10-07',format = '%Y-%m-%d').date()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM