Raj*_*ain 3 python csv datetime numpy pandas
我正在使用熊猫阅读 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
Run Code Online (Sandbox Code Playgroud)
df = pd.read_csv(file)
Run Code Online (Sandbox Code Playgroud)
现在我的业务需求是我想知道哪一列是纯日期字段、纯时间字段,或者哪一列是完整的日期时间。对于特定列,我的代码是:
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
Run Code Online (Sandbox Code Playgroud)
我的代码的问题是当只有时间字段时,pd.to_datetime 将默认为今天的日期,所以我无法将它与日期时间区分开来。有什么简单的解决办法吗?请帮我填写上面代码中的“东西”
如果想要测试时间,pandas 默认使用今天的日期,因此可能的解决方案是使用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
Run Code Online (Sandbox Code Playgroud)
另一个想法也是测试数字列是否默认返回非数字以防止将数字转换为日期时间,但如果可能,所有日期时间仅包含今天的日期(f
列),然后测试时间与Series.str.contains
匹配模式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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1790 次 |
最近记录: |