문제 설명
시계열 분석을 위해 Pandas Groupby 및 date_range를 사용하는 동안 오류가 발생했습니다. (Error using Pandas Groupby and date_range for timeseries analysis)
아래와 유사한 Pandas DataFrame이 있고 DataFrame을 1주일 길이의 청크로 분할하고 각 청크에서 함수를 실행하려고 합니다. groupby
및 date_range
함수로 이 작업을 수행할 수 있어야 한다고 생각하지만 문제가 있습니다.
다른 사람들이 날짜를 색인으로 사용하여 비슷한 일을 하는 것을 보았습니다. 그러나 df의 여러 행이 같은 날짜를 가질 수 있으므로 이 상황에서는 작동하지 않습니다. 또한 모든 날짜는 df에 표시되지 않습니다.
groupby
및/또는 date_range
기능에 내가 무엇을 잘못하고 있습니까?
이것이 파악되면 nx.from_pandas_dataframe
을 사용하고 싶습니다.
참조 솔루션
방법 1:
There are probably better ones, but here is one solution. I create a dictionary of dataframes keyed off of the year/week tuple pair.
First, I create a column in the dataframe of year/week tuple pairs. Then I use a dictionary comprehension to group on this column.
df['year_week'] = [(d.year, d.week) for d in df['date']]
weekly_groups = {w: g for w, g in df.groupby('year_week')}
>>> weekly_groups
{(2015, 49): source target date year_week
0 e a1 2015‑12‑02 (2015, 49)
1 e a2 2015‑12‑02 (2015, 49)
2 e a3 2015‑12‑03 (2015, 49)
3 e a4 2015‑12‑04 (2015, 49)
4 e a5 2015‑12‑04 (2015, 49),
(2015, 50): source target date year_week
5 e a1 2015‑12‑08 (2015, 50)
6 e a2 2015‑12‑09 (2015, 50)
7 e a6 2015‑12‑09 (2015, 50)
8 e a7 2015‑12‑13 (2015, 50),
(2015, 51): source target date year_week
9 e a1 2015‑12‑15 (2015, 51)
10 e a6 2015‑12‑16 (2015, 51)
11 e a8 2015‑12‑17 (2015, 51)
12 e a9 2015‑12‑18 (2015, 51)}