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'
uj5u.com熱心網友回復:
使用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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366380.html
下一篇:檢查兩個分類變數是否幾乎相同
