【问题标题】:Trouble adding season column based on a datetime object基于日期时间对象添加季节列时遇到问题
【发布时间】:2021-08-06 13:17:23
【问题描述】:

我正在尝试完成我的工作项目,但我卡在某个点上。

我拥有的部分数据框是这样的:

year_month year month
2007-01 2007 1
2009-07 2009 7
2010-03 2010 3

但是,我想添加“季节”列。我正在说明足球赛季,赛季专栏需要说明球员踢的赛季。所以如果month等于或小于3,“season”列需要对应((year-1),“/”,year),如果大于(year,“/”,(year + 1))。 该表应如下所示:

year_month year month season
2007-01 2007 1 2006/2007
2009-07 2009 7 2009/2010
2010-03 2010 3 2009/2010

希望其他人可以帮助我解决这个问题。

这是创建第一个表的代码:

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'])

提前致谢!

【问题讨论】:

    标签: python pandas dataframe multiple-columns


    【解决方案1】:

    可以使用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
    

    【讨论】:

      【解决方案2】:

      您可以使用带有条件的 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
      

      【讨论】:

      • 感谢您的快速回复!
      猜你喜欢
      • 2021-07-25
      • 1970-01-01
      • 2017-10-22
      • 2023-03-23
      • 2014-11-08
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 2014-03-23
      相关资源
      最近更新 更多