1. 填充nan 使用fillna
- 以下小点参考之前的文章
- 指定列填充nan值
- lanbda 用法
- isinstance isinstance(x, datetime.datetime) 判断 是否是datetime.datetime 类型
- 三元表达式 lambda x: x.strftime(‘%Y-%m-%d’) if isinstance(x, datetime.datetime) else x
# "截至日期" 为指定的列 "无日期 为填充的值
values = {"截止日期": "无日期"}
new_data = data.fillna(value=values)
# 将0值填充为 无日期
new_data.loc[new_data["截止日期"] == 0] = "无日期"
# 将时间格式转化为字符串格式
new_data["截止日期"] = new_data["截止日期"].map(lambda x: x.strftime('%Y-%m-%d') if isinstance(x, datetime.datetime) else x)
2. pandas 某一列的时间格式
代码 时间处理
def convert_time(x):
# 获取当前日期 2022-05-05
now_time = str(datetime.datetime.now().date())
# 转化成时间格式, 下面需要计算
new_now_time = datetime.datetime.strptime(now_time, '%Y-%m-%d')
if x == "无日期":
return "无日期"
elif x == "长期" or x == "长期有效":
return "长期"
# 处理非特殊情况
else:
x_time = datetime.datetime.strptime(x, '%Y-%m-%d')
tem = (x_time - new_now_time).days
if tem >= 0:
if x.split("-")[0] == now_time.split("-")[0] and \
int(x.split("-")[1]) == int(now_time.split("-")[1]):
return "本月到期"
elif x.split("-")[0] == now_time.split("-")[0] and \
int(x.split("-")[1]) != int(now_time.split("-")[1]):
return "今年到期"
else:
return "未到期"
else:
if x.split("-")[0] == now_time.split("-")[0] and \
int(x.split("-")[1]) == int(now_time.split("-")[1]):
return "本月已到期"
elif x.split("-")[0] == now_time.split("-")[0] and \
int(x.split("-")[1]) != int(now_time.split("-")[1]):
return "今年已到期"
else:
return "已到期"
效果