本文介绍了行的min()和max()对于具有NaN的列失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取包含日期的两列的按行最大值(和最小值)

I am trying to take the rowwise max (and min) of two columns containing dates

from datetime import date
import pandas as pd
import numpy as np    

df = pd.DataFrame({'date_a' : [date(2015, 1, 1), date(2012, 6, 1),
                               date(2013, 1, 1), date(2016, 6, 1)],
                   'date_b' : [date(2012, 7, 1), date(2013, 1, 1), 
                               date(2014, 3, 1), date(2013, 4, 1)]})

df[['date_a', 'date_b']].max(axis=1)
Out[46]: 
0    2015-01-01
1    2013-01-01
2    2014-03-01
3    2016-06-01

符合预期.但是,如果数据帧包含单个NaN值,则整个操作将失败

as expected. However, if the dataframe contains a single NaN value, the whole operation fails

df_nan = pd.DataFrame({'date_a' : [date(2015, 1, 1), date(2012, 6, 1),
                                   np.NaN, date(2016, 6, 1)],
                       'date_b' : [date(2012, 7, 1), date(2013, 1, 1), 
                                   date(2014, 3, 1), date(2013, 4, 1)]})

df_nan[['date_a', 'date_b']].max(axis=1)
Out[49]: 
0   NaN 
1   NaN
2   NaN
3   NaN
dtype: float64

这是怎么回事?我期待这个结果

What is going on here? I was expecting this result

0    2015-01-01
1    2013-01-01
2    NaN
3    2016-06-01

如何实现?

推荐答案

我会说最好的解决方案是使用适当的dtype.熊猫提供了很好集成的datetime dtype.因此请注意,您正在使用object dtypes ...

I would say the best solution is to use the appropriate dtype. Pandas provides a very well integrated datetime dtype. So note, you are using object dtypes...

>>> df
       date_a      date_b
0  2015-01-01  2012-07-01
1  2012-06-01  2013-01-01
2         NaN  2014-03-01
3  2016-06-01  2013-04-01
>>> df.dtypes
date_a    object
date_b    object
dtype: object

但是请注意,当您使用

>>> df2 = df.apply(pd.to_datetime)
>>> df2
      date_a     date_b
0 2015-01-01 2012-07-01
1 2012-06-01 2013-01-01
2        NaT 2014-03-01
3 2016-06-01 2013-04-01
>>> df2.min(axis=1)
0   2012-07-01
1   2012-06-01
2   2014-03-01
3   2013-04-01
dtype: datetime64[ns]

这篇关于行的min()和max()对于具有NaN的列失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 22:20