我正在使用熊猫阅读csv
str,date,float,time,datetime
a,10/11/19,1.1,10:30:00,10/11/19 10:30
b,10/11/19,1.2,10:00:00,10/11/19 10:30
c,10/11/19,1.3,11:10:11,10/11/19 10:30
df = pd.read_csv(file)
现在我的业务需求是我想告诉哪一列是纯日期字段,纯时间字段或哪一列是完整的日期时间。对于特定的列,我的代码是:
try:
dt = pd.to_datetime(df[col])
dates = [obj.date() for obj in dt]
times = [obj.time() for obj in dt]
if dates and (set(times) == set([datetime.time(0, 0)])):
# Its a pure date field
elif <something>:
# Its a pure time field
else:
#Its a Datetime field
except:
# its not a datefield
我的代码存在问题,当只有时间字段时,pd.to_datetime使用默认的今天日期,因此我无法将其与datetime区分开。有什么简单的解决方案吗?请帮助我在上面的代码中填写“内容”
答案 0 :(得分:3)
如果需要测试时间,则默认情况下,大熊猫会使用今天的日期,因此可能的解决方案是,如果所有列值都匹配,则用Series.dt.date
,Timestamp.date
和Series.all
对其进行测试。
还为测试日期添加了另一种解决方案-测试Series.dt.floor
删除时间后是否具有相同的值:
df = pd.DataFrame({'a':['2019-01-01 12:23:10',
'2019-01-02 12:23:10'],
'b':['2019-01-01',
'2019-01-02'],
'c':['12:23:10',
'15:23:10'],
'd':['a','b']})
print (df)
a b c d
0 2019-01-01 12:23:10 2019-01-01 12:23:10 a
1 2019-01-02 12:23:10 2019-01-02 15:23:10 b
def check(col):
try:
dt = pd.to_datetime(df[col])
if (dt.dt.floor('d') == dt).all():
return ('Its a pure date field')
elif (dt.dt.date == pd.Timestamp('now').date()).all():
return ('Its a pure time field')
else:
return ('Its a Datetime field')
except:
return ('its not a datefield')
print (check('a'))
print (check('b'))
print (check('c'))
print (check('d'))
Its a Datetime field
Its a pure date field
Its a pure time field
its not a datefield
另一个想法是测试数值列是否默认情况下不返回数值,以防止将数值强制转换为日期时间,但是如果可能的话,所有日期时间仅包含今天的日期(f
列),则测试时间与{{ 3}}用于匹配模式HH:MM:SS
或H:MM:SS
:
df = pd.DataFrame({'a':['2019-01-01 12:23:10',
'2019-01-02'],
'b':['2019-01-01',
'2019-01-02'],
'c':['12:23:10',
'15:23:10'],
'd':['a','b'],
'e':[1,2],
'f':['2019-11-13 12:23:10',
'2019-11-13'],})
print (df)
a b c d e f
0 2019-01-01 12:23:10 2019-01-01 12:23:10 a 1 2019-11-13 12:23:10
1 2019-01-02 2019-01-02 15:23:10 b 2 2019-11-13
def check(col):
if np.issubdtype(df[col].dtype, np.number):
return ('its not a datefield')
try:
dt = pd.to_datetime(df[col])
if (dt.dt.floor('d') == dt).all():
return ('Its a pure date field')
elif df[col].str.contains(r"^\d{1,2}:\d{2}:\d{2}$").all():
return ('Its a pure time field')
else:
return ('Its a Datetime field')
except:
return ('its not a datefield')
print (check('a'))
print (check('b'))
print (check('c'))
print (check('d'))
print (check('e'))
print (check('f'))
Its a Datetime field
Its a pure date field
Its a pure time field
its not a datefield
its not a datefield
Its a Datetime field