无法根据日期时间对象添加季节列
Trouble adding season column based on a datetime object
我正在努力完成我的工作项目,但我卡在了某个点上。
我的部分数据框是这样的:
year_month
year
month
2007-01
2007
1
2009-07
2009
7
2010-03
2010
3
但是,我想添加“季节”列。我正在说明足球赛季,赛季栏需要说明球员参加的赛季。因此,如果月份等于或小于 3,则“季节”列需要对应于 ((year-1), "/", year),如果大于则对应于 (year, "/", (year + 1))。
table 应如下所示:
year_month
year
month
season
2007-01
2007
1
2006/2007
2009-07
2009
7
2009/2010
2010-03
2010
3
2009/2010
希望有人能帮我解决这个问题。
这是创建第一个 Table 的代码:
import pandas as pd
from datetime import datetime
df = pd.DataFrame({'year_month':["2007-01", "2009-07", "2010-03"],
'year':[2007, 2009, 2010],
'month':[1, 7, 3]})
# convert the 'Date' columns to datetime format
df['year_month']= pd.to_datetime(df['year_month'])
提前致谢!
您可以使用带条件的 lambda 函数,axis=1
将其应用于每一行。使用 f-Strings
减少了将值从 year
列转换为新 season
列所需的字符串所需的代码。
df['season'] = df.apply(lambda x: f"{x['year']-1}/{x['year']}" if x['month'] <= 3 else f"{x['year']}/{x['year']+1}", axis=1)
输出:
year_month year month season
0 2007-01 2007 1 2006/2007
1 2009-07 2009 7 2009/2010
2 2010-03 2010 3 2009/2010
可以使用np.where()
指定条件,根据条件的True
/False
得到对应的字符串,如下:
df['season'] = np.where(df['month'] <= 3,
(df['year'] - 1).astype(str) + '/' + df['year'].astype(str),
df['year'].astype(str) + '/' + (df['year'] + 1).astype(str))
结果:
year_month year month season
0 2007-01-01 2007 1 2006/2007
1 2009-07-01 2009 7 2009/2010
2 2010-03-01 2010 3 2009/2010
我正在努力完成我的工作项目,但我卡在了某个点上。
我的部分数据框是这样的:
year_month | year | month |
---|---|---|
2007-01 | 2007 | 1 |
2009-07 | 2009 | 7 |
2010-03 | 2010 | 3 |
但是,我想添加“季节”列。我正在说明足球赛季,赛季栏需要说明球员参加的赛季。因此,如果月份等于或小于 3,则“季节”列需要对应于 ((year-1), "/", year),如果大于则对应于 (year, "/", (year + 1))。 table 应如下所示:
year_month | year | month | season |
---|---|---|---|
2007-01 | 2007 | 1 | 2006/2007 |
2009-07 | 2009 | 7 | 2009/2010 |
2010-03 | 2010 | 3 | 2009/2010 |
希望有人能帮我解决这个问题。
这是创建第一个 Table 的代码:
import pandas as pd
from datetime import datetime
df = pd.DataFrame({'year_month':["2007-01", "2009-07", "2010-03"],
'year':[2007, 2009, 2010],
'month':[1, 7, 3]})
# convert the 'Date' columns to datetime format
df['year_month']= pd.to_datetime(df['year_month'])
提前致谢!
您可以使用带条件的 lambda 函数,axis=1
将其应用于每一行。使用 f-Strings
减少了将值从 year
列转换为新 season
列所需的字符串所需的代码。
df['season'] = df.apply(lambda x: f"{x['year']-1}/{x['year']}" if x['month'] <= 3 else f"{x['year']}/{x['year']+1}", axis=1)
输出:
year_month year month season
0 2007-01 2007 1 2006/2007
1 2009-07 2009 7 2009/2010
2 2010-03 2010 3 2009/2010
可以使用np.where()
指定条件,根据条件的True
/False
得到对应的字符串,如下:
df['season'] = np.where(df['month'] <= 3,
(df['year'] - 1).astype(str) + '/' + df['year'].astype(str),
df['year'].astype(str) + '/' + (df['year'] + 1).astype(str))
结果:
year_month year month season
0 2007-01-01 2007 1 2006/2007
1 2009-07-01 2009 7 2009/2010
2 2010-03-01 2010 3 2009/2010