2017-12-01 3 views
1

팬더 그룹의 데이터 프레임을 CSV로 출력하고 싶습니다. 다양한 StackOverflow 솔루션을 시도했지만 작동하지 않았습니다.팬더 그룹으로 to_csv

week_grouped = df.groupby('week') 
week_grouped.sum() #At this point you have the groupby result 
week_grouped.to_csv('week_grouped.csv') #Can't do this - .to_csv is not a df function. 
:

id month year count 
week     
0 9066 82 32142 895 
1 7679 84 30112 749 
2 8368 126 42187 872 
3 11038 102 34165 976 
4 8815 117 34122 767 
5 10979 163 50225 1252 
6 8726 142 38159 996 
7 5568 63 26143 582 

같은이

week count 
0 895 
1 749 
2 872 
3 976 
4 767 
5 1252 
6 996 
7 582 

현재 코드를 보이는 CSV를 원하십니까 :

파이썬 3.6.1, 팬더는 0.20.1

GROUPBY 결과는 같다

읽기 SO solu TIONS :

output groupby to csv file pandas

week_grouped.drop_duplicates().to_csv('week_grouped.csv') 

결과 : AttributeError : 호출 속성에 액세스 할 수 없습니다 'drop_duplicates' 'DataFrameGroupBy'객체, '적용'방법

Python pandas - writing groupby output to file

week_grouped.reset_index().to_csv('week_grouped.csv') 
를 사용해보십시오

검색 결과 : AttributeError : 'DataFrameGroupBy'객체의 호출 가능 속성 'reset_index'에 액세스 할 수 없습니다. '적용'메소드를 사용하십시오.

답변

2

두 번째 줄을 week_grouped = week_grouped.sum()으로 변경하고 세 줄을 모두 다시 실행 해보십시오.

당신이 자신의 Jupyter 노트북 셀에 week_grouped.sum()를 실행하면, 당신은 볼 방법 대신 week_grouped 결과를 다시 할당하는 문 반환 셀의 출력으로 출력. 일부 팬더 메소드는 inplace=True 개의 인수 (예 : df.sort_values(by=col_name, inplace=True))를 갖지만 sum은 그렇지 않습니다.

편집 : 매주 번호는 CSV에 한 번만 표시됩니까?

df = pd.read_csv('input.csv') 
df[['id', 'count']].to_csv('output.csv') 
+0

동일하게하기위한 것입니다. 이 경우 groupby는 함께 주를 모으는 데 사용되어 주당 계산을 할 수 있습니다. – kalmdown

+1

BTW - 'sum'이 왜 중요한지에 대한 설명에 많은 감사를드립니다. – kalmdown

0

나는 GROUPBY을 사용할 필요가없는 느낌, 당신은 단지 당신이 너무 원하지 않는 열을 삭제할 수 있습니다 : 그렇다면, 여기 groupby를 사용하지 않는 간단한 해결책이다.

df = df.drop(['month','year'],axis==1) 
df.reset_index() 
df.to_csv('Your path') 
+0

"axis = 1"이어야합니다. 그러나 예는 행을 출력하지만 주 또는 상태별로 그룹화되지는 않습니다. – kalmdown

0

이 일을보십시오 :

week_grouped = df.groupby('week') 
week_grouped.sum().reset_index().to_csv('week_grouped.csv') 

가 파일에 전체 dataframe을 쓸 것이다. 당신은 다음 두 열을 원하는 경우에, 여기
week_grouped = df.groupby('week') 
week_grouped.sum().reset_index()[['week', 'count']].to_csv('week_grouped.csv') 

는 원래 코드의 라인을 설명하여 줄입니다 :

# This creates a "groupby" object (not a dataframe object) 
# and you store it in the week_grouped variable. 
week_grouped = df.groupby('week') 

# This instructs pandas to sum up all the numeric type columns in each 
# group. This returns a dataframe where each row is the sum of the 
# group's numeric columns. You're not storing this dataframe in your 
# example. 
week_grouped.sum() 

# Here you're calling the to_csv method on a groupby object... but 
# that object type doesn't have that method. Dataframes have that method. 
# So we should store the previous line's result (a dataframe) into a variable 
# and then call its to_csv method. 
week_grouped.to_csv('week_grouped.csv') 

# Like this: 
summed_weeks = week_grouped.sum() 
summed_weeks.to_csv('...') 

# Or with less typing simply 
week_grouped.sum().to_csv('...') 
+1

고마워요! sum()이 to_csv 문에 포함되어 있지만 sum()이 자체 행에서 수행되는 경우에는 작동하지 않는 이유는 무엇입니까? – kalmdown

+0

답변을 업데이트 드리겠습니다 –

0

그룹 키는 그룹의 식별자입니다 반환 키, 값 쌍으로 값은 그룹 자체, 즉 키와 일치하는 원본 df의 하위 집합입니다.다음과 같이 예를 week_grouped = df.groupby('week')에서

는 구체적으로 탐구 할 수있는 그룹 (pandas.core.groupby.DataFrameGroupBy 객체)의 설정 :

for k, gr in week_grouped: 
    # do your stuff instead of print 
    print(k) 
    print(type(gr)) # This will output <class 'pandas.core.frame.DataFrame'> 
    print(gr) 
    # You can save each 'gr' in a csv as follows 
    gr.to_csv('{}.csv'.format(k)) 

을 또는 대안 당신은 당신의 그룹화 개체

에 집계 함수를 계산할 수 있습니다
result = week_grouped.sum() 
# This will be already one row per key and its aggregation result 
result.to_csv('result.csv') 

예를 들어, 기본적으로 pandas 개체가 불변이므로 일부 변수에 함수 결과를 할당해야합니다.

some_variable = week_grouped.sum() 
some_variable.to_csv('week_grouped.csv') # This will work 

기본적으로 result.csv 및 week_grouped.csv은 주 여러 행에 표시되는 원본 데이터에서

+0

자세한 설명을 해주셔서 감사합니다. 문제가 아니라 시스템을 이해하는 데 도움이됩니다. – kalmdown

관련 문제