首页 > 解决方案 > 不会返回空白日期行的 Pandas 函数

问题描述

我在熊猫中有一个像这样格式化的数据框。

(df)
ID     Num          Col 1        Col 2       Status       Date
1      6000TO6100   6000         6100        Active       2020-07-18
2      9-999        NaN          NaN         Active       2020-03-30
3      7000TO8000   7000         8000        Active       2020-07-18
4      9-999        NaN          NaN         Active       NaT
5      3800         NaN          NaN         Active       NaT
6      72-11        NaN          NaN         Active       2020-07-18

....

我做了一个这样的函数,它将返回输入数字的行,具体取决于数字是否在 Col 1 和 2 的范围内并且也处于活动状态。问题是对于像 9-999 这样的输入,它将返回

(df)
ID     Num          Col 1         Col 2        Status       Date
2      9-999        NaN           NaN         Active       2020-03-30
4      9-999        NaN           NaN         Active       NaT

但我想要的输出是

(df)
ID     Num          Col 1         Col 2        Status       Date
2      9-999        NaN           NaN         Active       2020-03-30

这是我的代码:

search = " "

try:
    int(search)
    check_col = df.loc[(df['Col 1'] <= int(search)) &  (df['Col 2'] >= int(search)) & (df['Status'] == 'Active')]
    if len(check_col) > 0:
        print(check_col)

except:
    pass

check_num = df.loc[(df['Status'] == 'Active') & (df['ID'] == str(search))]

if len(check_num) > 0:
        print(check_num)

我需要编辑此函数,以便解决方案中不会打印“日期”列中的空值。我正在考虑制作一个日期变量并说如果 Date 是 > 0 然后沿着(df['Date'] == 'NaT')返回 false 的行打印,但我不确定。我对python还是很陌生,所以感谢您的帮助。

标签: pythonpandasdataframe

解决方案


您可以dropna()在应用代码之前使用:

df = df.dropna(subset='Date')

推荐阅读