Convert a general date format to ISO week date format

I have this framework with this type of date format

           Date  Week Number   Influenza[it]  Febbre[it]  Rinorrea[it]  
0    2008-01-01             1            220         585           103   
1    2008-01-08             2            403         915           147   
2    2008-01-15             3            366         895           136   
3    2008-01-22             4            305         825           136   
4    2008-01-29             5            311         837           121 
... ...

I would like to convert the date format to the ISO week date format similar to this data framework (because I need to intersect two data frames with the same dates depending on the years and weeks). The format is similar to "year-weeknumber ofyear".

0     2007-42
1     2007-43
2     2007-44
3     2007-45
4     2007-46
... ...

So, I was able to simply find the ISO weeks of the first data frame this way:

wiki = pd.read_csv('file.csv', parse_dates=['Date'])
for i,d in wiki.iterrows():
    print d.Date.isocalendar()[1]

Conclusion:

1
2
3
4
...

But I do not know how to create a date format, for example, a second framework (in the "year-weeknumber ofheear" way)

+4
source share
2 answers

Instead of a read operation, you can use a vectorized approach:

df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%V')
df['Date']
0    2008-01
1    2008-02
2    2008-03
3    2008-04
4    2008-05
Name: Date, dtype: object

%V - , ISO 8601.


:

from io import StringIO
data = StringIO(
'''
Date     Week Number   Influenza[it]  Febbre[it]  Rinorrea[it]  
2008-01-01             1            220         585           103   
2008-01-08             2            403         915           147   
2008-01-15             3            366         895           136   
2008-01-22             4            305         825           136   
2008-01-29             5            311         837           121
''')
df = pd.read_csv(data, sep='\s{2,}', parse_dates=['Date'], engine='python')
df

enter image description here

df['Date'].dtypes
dtype('<M8[ns]')

df['Date'].dt.strftime('%Y-%V')
0    2008-01
1    2008-02
2    2008-03
3    2008-04
4    2008-05
Name: Date, dtype: object

: ( , )

L = ['{}-{}'.format(d.Date.isocalendar()[0], str(d.Date.isocalendar()[1]).zfill(2)) for i,d in wiki.iterrows()]

series:

>>> pd.Series(L)
0    2008-01
1    2008-02
2    2008-03
3    2008-04
4    2008-05
dtype: object
+4

time.strftime('% Y-% W') . .

import pandas pd pd.to_datatime (time.time()). STRFTIME ( '% Y-% W') '1970-00'

0

Source: https://habr.com/ru/post/1663856/


All Articles