gpt4 book ai didi

python - 从具有 NA 值的 Date 获取 Year & Month 作为字符串

转载 作者:太空宇宙 更新时间:2023-11-04 04:43:17 24 4
gpt4 key购买 nike

这是当前 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)

问题是当我从日期中提取年份和月份时,它将返回 float 类型。

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 在该行是空的。

最佳答案

您应该使用 pd.Series.dt.strftime 直接从 Date 执行字符串转换.

这不仅确保 NaT 行保持 NaT,而且字符串的格式更好,例如几个月的零填充。

df["yyyy_mm"] = df['Date'].dt.strftime('%Y-%m')

print(df)

ID Date Year Month yyyy_mm
0 1 2017-03-29 2017.0 3.0 2017-03
1 2 NaT NaN NaN NaT
2 3 2015-11-05 2015.0 11.0 2015-11
3 4 NaT NaN NaN NaT
4 5 2017-02-28 2017.0 2.0 2017-02

关于python - 从具有 NA 值的 Date 获取 Year & Month 作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com