python日期格式不正确就删除数据
时间: 2023-08-02 19:31:46 浏览: 45
对于删除日期格式不正确的数据,可以通过以下步骤实现:
1. 首先,使用 Python 的 datetime 模块检查日期格式是否正确,如果格式不正确,则将该行数据标记为需要删除的数据。
2. 然后,使用 Python 的 Pandas 模块读取数据,并使用 drop 函数删除标记为需要删除的数据。
以下是一个示例代码:
```python
import pandas as pd
from datetime import datetime
# 读取数据
df = pd.read_csv('data.csv')
# 检查日期格式是否正确,并将需要删除的数据标记为 True
to_delete = []
for index, row in df.iterrows():
try:
datetime.strptime(row['date'], '%Y-%m-%d')
to_delete.append(False)
except ValueError:
to_delete.append(True)
# 删除标记为 True 的数据
df.drop(df[to_delete].index, inplace=True)
# 保存数据
df.to_csv('clean_data.csv', index=False)
```
在上述代码中,我们首先使用 Pandas 模块读取数据,并使用 datetime 模块检查日期格式是否正确。如果日期格式不正确,则将该行数据标记为需要删除的数据,否则标记为不需要删除的数据。然后,我们使用 Pandas 的 drop 函数删除标记为需要删除的数据,并保存数据到另一个文件中。