在"for"循环中处理 dtype



我正在使用 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')
您可以使用

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

然后,您可以只了解这些列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

最新更新