昨天遇到一个问题,怎么把时间按条件分类。
这个问题让我忙活了很久。数据是从csv
中导入的,主要想根据不同时间范围划分几类。
一开始我将时间字段和'2018-03-15'
相比大小,结果出了问题。csv
中导入的时间字段也是字符串,这是字符串之间的比较,得不到想要的结果。写函数进行处理的时候,也搞混了很多问题。最后成功了,总结一下。
利用pandas
导入csv
,然后对时间列进行处理。首先要对字符串的时间转为datetime
,然后对每个时间进行处理。利用循环,返回list
;利用apply
,针对每个元素处理。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas
from datetime import datetime
df=pandas.read_csv(open(file='test.csv'))
# 把字符串时间变为datetime
df['time']=pandas.to_datetime(df['时间'])
# 设定标准
a=datetime(2018,3,15)
# 循环函数
def test(times):
results=[]
for x in times:
if x<a:
results.append(1)
else:
results.append(0)
return results
# 利用循环函数,分类时间
df['categories1']=test(df['time'])
# 利用apply处理
df['categories2']=df['time'].apply(lambda x:test(x))
print(df)
pandas
的每一列是Series
,本质上就是一个list
,apply
针对每个元素处理,直接利用函数就要返回list
。