这里针对特定案例描述了问题,但它对许多类似项目很有值(value)。
一个名为 month 的 pandas.series 包含每个样本的月份日期,格式为 int (1,2,3,4,...)。我想把它改成“01,02,03,...12”的样式,然后加上年份。
使用"{0:0=2d}".format(a) 和loop,可以轻松转换系列值:
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')
但是循环策略效率不高,有什么简单的方法可以达到同样的目的吗?
最佳答案
你可以使用apply
:
month.apply("{0:0=2d}".format)
时间
- Psidom 的方法
%timeit month.astype(str).str.zfill(2)
10 个循环,3 个循环中的最佳:每个循环 39.1 毫秒
- 这个方法:
%timeit month.apply("{0:0=2d}".format)
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
关于python - 将数字函数应用于 pandas.series 的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606662/