我正在使用for循环读取熊猫数据框中的列,并使用嵌套的if语句在datetime范围内找到最小值和最大值。

我可以识别所需的datetime列,但是找不到将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

10-07 19:43
查看更多