【问题标题】:add string based on conditional formating of a dataframe根据数据框的条件格式添加字符串
【发布时间】:2021-11-26 04:28:50
【问题描述】:
data = {"marks":[1,2,3,4,5,6,7,8,9,10,11,12], "month":['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']}
df2 = pd.DataFrame(data)

直到现在我尝试了以下但没有得到上面提到的:

for i in df2['month']:
   if (i=='jan' or i=='feb' or i=='mar'):
        df2['q'] = '1Q'
   else:
        df2['q']='other'

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用Series.dt.quarter 将列转换为日期时间并添加q

    df2['new'] = 'q' + pd.to_datetime(df2['month'], format='%b').dt.quarter.astype(str)
    

    或者通过字典使用Series.map

    d = {'jan':'q1', 'feb':'q1','mar':'q1',
         'apr':'q2','may':'q2', 'jun':'q2',
         'jul':'q3','aug':'q3', 'sep':'q3',
         'oct':'q4','nov':'q4', 'dec':'q4'}
        
    df2['new'] = df2['month'].map(d)
    

    【讨论】:

      猜你喜欢
      • 2016-09-08
      • 1970-01-01
      • 2021-07-23
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      相关资源
      最近更新 更多