我使用for循环读取pandas数据框中的列,使用嵌套的if语句查找日期时间范围内的最小值和最大值。
我可以识别我需要的日期时间列,但无法找到将column
变量传递到dataframe.series.min()
和max
语句的正确方法。
import pandas as pd
data = pd.somedata()
for column in data.columns:
if data[column].dtype == 'datetime64[ns]':
data.column.min()
data.column.max()
所以当传递column
变量时,循环应返回日期时间值,如下所示:
data.DFLT_DT.min()
Timestamp('2007-01-15 00:00:00')
data.DFLT_DT.max()
Timestamp('2016-10-18 00:00:00')
答案 0 :(得分:1)
您可以使用select_dtypes
来实现此目的:
In [104]:
df = pd.DataFrame({'int':np.arange(5), 'flt':np.random.randn(5), 'str':list('abcde'), 'dt':pd.date_range(dt.datetime.now(), periods=5)})
df
Out[104]:
dt flt int str
0 2017-01-18 16:50:13.678037 -0.319022 0 a
1 2017-01-19 16:50:13.678037 0.400441 1 b
2 2017-01-20 16:50:13.678037 0.114614 2 c
3 2017-01-21 16:50:13.678037 1.594350 3 d
4 2017-01-22 16:50:13.678037 -0.962520 4 e
In [106]:
df.select_dtypes([np.datetime64])
Out[106]:
dt
0 2017-01-18 16:50:13.678037
1 2017-01-19 16:50:13.678037
2 2017-01-20 16:50:13.678037
3 2017-01-21 16:50:13.678037
4 2017-01-22 16:50:13.678037
然后你可以在这些cols上获得min,max
:
In [108]:
for col in df.select_dtypes([np.datetime64]):
print('column: ', col)
print('max: ',df[col].max())
print('min: ',df[col].min())
column: dt
max: 2017-01-22 16:50:13.678037
min: 2017-01-18 16:50:13.678037
要回答尝试失败的原因,您要将np.dtype
对象与字符串进行比较,并希望与np.dtype.name
进行比较:
In [125]:
for col in df:
if df[col].dtype.name == 'datetime64[ns]':
print('col', col)
print('max', df[col].max())
print('min', df[col].min())
col dt
max 2017-01-22 16:50:13.678037
min 2017-01-18 16:50:13.678037