2017-06-17 45 views
2

這裏針對特定情況描述了該問題,但對於許多類似的項目來說這將是有價值的。將數字的函數應用於pandas.series的快速方法

一個pandas.series稱爲個月包含每個樣本的月份日期的INT格式(1,2,3,4,...)。我想將它改成「01,02,03,... 12」的樣式,然後再添加一年。

使用「{0:0 = 2D}」 的格式(A),該系列值可以很容易地轉化:

df['date'] = np.nan 
for i in range(0,len(df),1): 
    df.date.iloc[i] = df.year.iloc[i] +"-"+'%2d'%df.month.values.iloc[i] 
### df.date is a new series contain the year-month('2017-01','2017-02') 

但循環策略是未效率,是有沒有簡單的方法來實現相同的目標?

回答

3

您可以轉換個月str類型,然後使用str.zfill

month = pd.Series([1,2,12]) 

month.astype(str).str.zfill(2) 

#0 01 
#1 02 
#2 12 
#dtype: object 

要使用一年串連它:

df.year.astype(str) + '-' + df.month.astype(str).str.zfill(2) 
4

您可以使用apply

month.apply("{0:0=2d}".format) 

TIMIN克

  • Psidom的方法

%timeit month.astype(STR).str.zfill(2)

10循環,最好的3:每次循環39.1毫秒

  • 此方法:

%timeit month.apply( 「{0:0 = 2D}」 的格式。)

100個循環,最好的3:每次循環7.93毫秒

df = pd.DataFrame({'month':pd.np.random.randint(1,12,10000),'year':pd.np.random.choice([i for i in range(2004,2017)],10000)}) 

df.year.astype(str) + '-' + df.month.apply("{0:0=2d}".format) 

輸出:

0  2014-10 
1  2012-04 
2  2015-03 
3  2014-05 
4  2007-03 
5  2008-04 
2

您可以在具有相應命名列的數據框上使用pd.to_datetime來創建一系列日期時間對象。

考慮數據框df

df = pd.DataFrame(dict(year=[2011, 2012], month=[3, 4])) 
df 

    month year 
0  3 2011 
1  4 2012 

所有我們缺少的是day列。如果再加上它,我們可以把它傳遞給pd.to_datetime

pd.to_datetime(df.assign(day=1)) 

0 2011-03-01 
1 2012-04-01 
dtype: datetime64[ns] 

嗯,這很方便。怎麼辦?

pd.to_datetime(df.assign(day=1)).apply('{:%Y-%m}'.format) 

0 2011-03 
1 2012-04 
dtype: object 

或者

pd.to_datetime(df.assign(day=1)).dt.strftime('%Y-%m') 

0 2011-03 
1 2012-04 
dtype: object 

創建一個新的列

df.assign(year_month=pd.to_datetime(df.assign(day=1)).dt.strftime('%Y-%m')) 

    month year year_month 
0  3 2011 2011-03 
1  4 2012 2012-04 

但是,我們可以剛纔做

df.assign(year_month=df.apply(lambda x: '{year}-{month:02d}'.format(**x), 1)) 

    month year year_month 
0  3 2011 2011-03 
1  4 2012 2012-04 
+1

並在效率方面;字符串方法可能會在構建階段勝過這一點,但隨着日期的推移,事後您可能會更快更容易。 – ayhan