python - Pandas:如何删除包含无效月/日列组合的行,例如 2 月 30 日?

标签 python pandas

我的源数据使用 31 列作为日期值,每个月一行。我已将 31 天的列合并为一天列,现在我想将年、月和日列合并到日期时间(?)列中,以便我可以按年/月/日对行进行排序。

融化后,我的数据框如下所示:

       year  month day   prcp
0      1893      1  01    0.0
1      1893      2  01    0.0
2      1893      3  01    0.0
3      1893      4  01    NaN
4      1893      5  01    NaN
5      1893      6  01    NaN
6      1893      7  01    NaN
7      1893      8  01    0.0
8      1893      9  01   10.0
9      1893     10  01    0.0
10     1893     11  01    0.0
11     1893     12  01    NaN
12     1894      1  01    NaN
13     1894      2  01    0.0
14     1894      3  01    NaN
...

接下来,我尝试创建一个可以排序的“时间”列,使用年、月和日列作为日期时间构造函数的参数。我试过使用这种方法来做到这一点:

def make_datetime(y, m, d):
    return(datetime(year=y, month=m, day=d))

df['time'] = np.vectorize(make_datetime)(df['year'].astype(int), df['month'].astype(int), df['day'].astype(int))

以上不会让我到达那里,因为在月份/日期列在一起没有意义的情况下它会失败,例如非闰年的 2 月 29 日,4 月 31 日等。我认为我接下来要做的是以某种方式将 datetime() 调用包装在 try/catch 中,当它由于不兼容的月/日组合而发出声音时,我应该将行放在 catch block 中。如果不对所有行进行 for 循环,我将如何去做呢?或者有更好的方法来解决这个问题吗?

最佳答案

您可以直接将 df 传递给 to_datetime

pd.to_datetime(df,errors='coerce')
Out[905]: 
#          NaT
#          NaT
#   1892-02-29
#          NaT
#          NaT
#          NaT
#   1896-02-29
#          NaT
#          NaT
dtype: datetime64[ns]
df['New']=pd.to_datetime(df,errors='coerce')
df.dropna()
Out[907]: 
   year  month  day        New
#  1892      2   29 1892-02-29
#  1896      2   29 1896-02-29

关于python - Pandas:如何删除包含无效月/日列组合的行,例如 2 月 30 日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059717/

相关文章:

python - 如何从数据框中删除/替换任何字符串?

python - 尾递归函数无法返回值(Python 3)

python - 数据集形状不匹配 Conv1D 输入层

python - 从终端启动和使用 popen 启动之间的 OpenOffice 行为差异 - 均在 chroot 中

python - 遍历目录中的文件,在 Pandas 中添加日期列

python - Python 中文件的动态名称

Python/Pandas Dataframe - 当 0 时将小数精度替换为 int 值,否则四舍五入到 n 位小数

python - 在组框中对小部件进行分组

python - 将转换器与 read_csv 一起使用时获取错误行

python - 我怎样才能用一系列的 Pandas 查找?