如何在pandas python中的isocalendar函数中应用系列

时间:2018-01-02 09:16:44

标签: python pandas datetime

我有下表:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c As Range
    For Each c In Target
        Debug.Print c.Address
    Next c
End Sub

我希望使用 isocalender 来获得工作周,所以任何想法都可以与我分享?

Time                     
2016-09-10T23:20:00.000000000
2016-08-10T23:20:00.000000000
2016-09-10T23:20:00.000000000
2017-09-10T23:20:00.000000000
2016-09-10T23:20:00.000000000

1 个答案:

答案 0 :(得分:2)

您可以使用:

#convert column to datetime
df['Time'] = pd.to_datetime(df['Time'])

#simplier solution with strftime
df['WW'] = df['Time'].dt.strftime('%Y-%V')
#solution with isocalendar
df['WW1'] = df['Time'].apply(lambda x: str(x.isocalendar()[0]) + '-' + 
                                       str(x.isocalendar()[1]).zfill(2))
print (df)
                 Time       WW      WW1
0 2016-09-10 23:20:00  2016-36  2016-36
1 2016-08-10 23:20:00  2016-32  2016-32
2 2016-09-10 23:20:00  2016-36  2016-36
3 2017-09-10 23:20:00  2017-36  2017-36
4 2016-09-10 23:20:00  2016-36  2016-36

如果不想改变第一栏:

datetimes = pd.to_datetime(df['Time'])

df['WW'] = datetimes.dt.strftime('%Y-%V')

df['WW1'] = datetimes.apply(lambda x: str(x.isocalendar()[0]) + '-' + 
                                      str(x.isocalendar()[1]).zfill(2))
print (df)
                            Time       WW      WW1
0  2016-09-10T23:20:00.000000000  2016-36  2016-36
1  2016-08-10T23:20:00.000000000  2016-32  2016-32
2  2016-09-10T23:20:00.000000000  2016-36  2016-36
3  2017-09-10T23:20:00.000000000  2017-36  2017-36
4  2016-09-10T23:20:00.000000000  2016-36  2016-36