Python 将数字函数应用于pandas.series的快速方法

Python 将数字函数应用于pandas.series的快速方法,python,pandas,numpy,Python,Pandas,Numpy,这里针对具体的案例描述了这个问题,但是对于许多类似的项目来说,它是有价值的 一个名为month的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] +"-"+'%2

这里针对具体的案例描述了这个问题,但是对于许多类似的项目来说,它是有价值的

一个名为month的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')
但是循环策略是无效的,有没有简单的方法来实现相同的目标?

您可以将月份转换为
str
类型,然后使用:

要将其与年份连接,请执行以下操作:

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

您可以使用
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}”。格式)

100圈,最佳3圈:每圈7.93毫秒

输出:

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

您可以在具有适当命名列的数据帧上使用
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\u 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


新建专栏

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

在效率方面,;字符串方法在构建阶段可能会比这更好,但是使用datetimes之后您将要做的事情可能会更快、更容易。
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