根据datetime列的值创建新的字符串列

2024-05-18 21:41:28 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码创建一个新列“季节”,该列根据日期列的值指定“季节”

df2.season = None
df2.loc[(df2.date=='2010-02-22 00:00:00'), 'season'] = '2009/2010'
df2.loc[(df2.date=='2011-02-22 00:00:00'), 'season'] = '2010/2011'
df2.loc[(df2.date=='2014-09-19 00:00:00'), 'season'] = '2014/2015'
df2.loc[(df2.date=='2012-02-22 00:00:00'), 'season'] = '2011/2012'
df2.loc[(df2.date=='2013-09-20 00:00:00'), 'season'] = '2013/2014'
df2.loc[(df2.date=='2015-09-10 00:00:00'), 'season'] = '2015/2016'
df2.head()

有没有一种方法可以通过循环减少代码行数

我尝试了pd.cut(),但由于日期列中的datetime值,因此出现了一个错误

我想有一种方法可以压缩日期和季节值,然后使用循环,但我不知道如何进行。谢谢


Tags: 方法代码nonedatetimedate错误headloc
1条回答
网友
1楼 · 发布于 2024-05-18 21:41:28

如果逻辑为去年6月日前后的日期时间,请使用:

df["date"] = pd.to_datetime(df["date"])

y = df["date"].dt.year
y1 = y.astype(str)
y2 = (y - 1).astype(str)
y3 = (y + 1).astype(str)

df["season"] = np.where(df["date"].dt.month > 6, y1 + '/' + y3, y2 + '/' + y3)
print (df)
        date     season
0 2010-02-22  2009/2011
1 2011-02-22  2010/2012
2 2014-09-19  2014/2015
3 2012-02-22  2011/2013
4 2013-09-20  2013/2014
5 2015-09-10  2015/2016

相关问题 更多 >

    热门问题