【发布时间】:2018-05-03 17:11:38
【问题描述】:
这是当前的df:
ID Date
1 3/29/2017
2
3 11/5/2015
4
5 2/28/2017
我正在尝试将年 + 月作为新列中的字符串。这是我的代码:
df["Year"] = df["Date"].dt.year
df["Month"] = df["Date"].dt.month
df["yyyy_mm"] = df["Year"].map(str) + "-" + df["Month"].map(str)
问题是当我从日期中提取年份和月份时,它会返回浮点类型。
ID Date Year Month yyyy_mm I hope to get this
1 3/29/2017 2017.0 3.0 2017.0-3.0 2017-3
2 nan-nan
3 11/5/2015 2015.0 11.0 2015.0-11.0 2015-11
4 nan-nan
5 2/28/2017 2017.0 2.0 2017.0-2.0 2017-2
我尝试使用df["Date"].dt.year.astype(int) 将其转换为int,因此没有.0,但出现此错误:无法将非有限值(NA 或inf)转换为整数。因为列中有 NAN。
我不想用 0 或其他东西填充所有年份和月份,我只想让它们保持空白,因为 date 在该行是空的。
【问题讨论】: