【问题标题】:Pandas add a new column whose values depend on a specific conditions [duplicate]熊猫添加了一个新列,其值取决于特定条件[重复]
【发布时间】:2018-02-12 05:16:16
【问题描述】:

我有一个数据框,其中有一列名为“日期”;包含格式为月/日/年('01/01/2018')的日期。我想创建一个名为“月份”的新列,其中包含月份的名称,在本例中为一月。 显然我想每个月都这样做。

例如:

   Date         Month
0  01/01/2018   January
1  02/03/2018   February
2  04/08/2018   April

我该怎么做? 谢谢

【问题讨论】:

  • @SteffiKeranRaniJ 请阅读calendar 文档。提示:calendar.month_abbr 中的“_abbr”表示“缩写”。
  • 好的,我使用此链接解决了问题。谢谢
  • @DYZ calendar.month_name 会做

标签: python pandas


【解决方案1】:

我假设 df 中的“日期”是 string ,因此需要转换。 如果不是,则需要相应调整。

尝试关注

from datetime import date,datetime  #date needed for simulation.
import pandas as pd


l = ['01/01/2018','02/03/2018','04/08/2018']  
df = pd.DataFrame({'Date':l})

df['Month']=df['Date'].apply(lambda x :datetime.strptime(x, '%m/%d/%Y').strftime('%B'))

结果

>>> df
         Date     Month
0  01/01/2018   January
1  02/03/2018  February
2  04/08/2018     April
>>> 

【讨论】:

    【解决方案2】:

    这是解决问题的一种简单方法:

    代码

    import calendar
    import pandas as pd
    d = {'Date':['01/01/2018', '02/03/2018', '04/08/2018']}
    df1 = pd.DataFrame(d)
    df1['Month'] = pd.DatetimeIndex(df1['Date']).month
    df1['Month'] = df1['Month'].apply(lambda x: calendar.month_name[x])
    print(df1)
    

    执行此代码后,您将获得所需的结果:

    结果

             Date      Month
    0  01/01/2018    January
    1  02/03/2018   February
    2  04/08/2018      April
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 2021-07-26
      • 2022-01-26
      • 2015-06-28
      • 2018-10-26
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多