programing

날짜/시간별 판다 데이터 프레임 그룹

yellowcard 2023. 7. 19. 21:17
반응형

날짜/시간별 판다 데이터 프레임 그룹

CSV 파일을 고려합니다.

string,date,number
a string,2/5/11 9:16am,1.0
a string,3/5/11 10:44pm,2.0
a string,4/22/11 12:07pm,3.0
a string,4/22/11 12:10pm,4.0
a string,4/29/11 11:59am,1.0
a string,5/2/11 1:41pm,2.0
a string,5/2/11 2:02pm,3.0
a string,5/2/11 2:56pm,4.0
a string,5/2/11 3:00pm,5.0
a string,5/2/14 3:02pm,6.0
a string,5/2/14 3:18pm,7.0

이 정보를 읽고 날짜 열을 날짜 시간 형식으로 다시 포맷할 수 있습니다.

b = pd.read_csv('b.dat')
b['date'] = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')

나는 데이터를 월별로 분류하려고 노력해 왔습니다.그 달에 접속해서 그것으로 그룹화할 수 있는 확실한 방법이 있어야 할 것 같습니다.하지만 저는 그것을 할 수 없을 것 같아요.방법 아는 사람?

현재 제가 시도하고 있는 것은 다음 날짜까지 다시 인덱싱하는 것입니다.

b.index = b['date']

다음과 같이 월에 액세스할 수 있습니다.

b.index.month

하지만 매달 정리할 수 있는 기능을 찾을 수 없을 것 같습니다.

성공:

b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])

또는

b.groupby(pd.Grouper(freq='M'))  # update for v0.21+

(업데이트: 2018)

참고:pd.Timegrouper감가상각되어 제거됩니다.대신 사용:

 df.groupby(pd.Grouper(freq='M'))

시계열 데이터별로 그룹화하려면 방법을 사용할 수 있습니다.예를 들어, 월별로 그룹화하는 방법:

df.resample(rule='M', on='date')['Values'].sum()

오프셋 별칭이 있는 목록은 여기에서 찾을 수 있습니다.

MultiIndex를 방지하는 한 가지 해결책은 새 솔루션을 만드는 것입니다.datetime열 설정일 = 1.그런 다음 이 열을 기준으로 그룹화합니다.

월정규화일

df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
                   'Values': [5, 10, 15, 20]})

# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)

사용할 경우groupby정상:

g = df.groupby('YearMonth')

res = g['Values'].sum()

# YearMonth
# 2017-09-01    20
# 2017-10-01    30
# Name: Values, dtype: int64

과의 비교pd.Grouper

이 솔루션의 미묘한 이점은 다음과 같습니다.pd.Grouper그룹화 지수는 종료가 아닌 매월 시작으로 정규화되므로 다음을 통해 그룹을 쉽게 추출할 수 있습니다.get_group:

some_group = g.get_group('2017-10-01')

10월의 마지막 날을 계산하는 것은 약간 더 번거롭습니다. v0.23 기준으로, 다음을 지원합니다.convention매개 변수, 그러나 이것은 오직 a에 대해서만 적용됩니다.PeriodIndex그루퍼

문자열 변환과 비교

위 아이디어의 대안은 문자열로 변환하는 것입니다. 예를 들어 날짜 시간 변환2017-10-XX끈으로 묶는'2017-10'그러나 이 방법은 모든 효율성 이점을 잃기 때문에 권장되지 않습니다.datetime직렬(연속 메모리 블록에서 내부적으로 숫자 데이터로 표시됨) 대object일련의 문자열(포인터 배열로 표시됨).

@jpp에 대한 약간의 대체 솔루션이지만 출력은YearMonth문자열:

df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))

res = df.groupby('YearMonth')['Values'].sum()

언급URL : https://stackoverflow.com/questions/24082784/pandas-dataframe-groupby-datetime-month

반응형