2017-03-12 8 views
0

사용자가 올해에 넣는 함수를 만들려고합니다.이 Lynda class을 모델로 사용하여 지출로 상위 10 개국을 출력합니다. 여기 파이썬 상위 10 개 함수

나는이 코드를 시도하고 오류가있어

df.dtypes 
Country Name  object 
Country Code  object 
Year    int32 
CountryYear  object 
Population  int32 
GDP    float64 
MilExpend  float64 
Percent   float64 
dtype: object 



    Country Name Country Code Year CountryYear Pop   GDP Expend Percent 
0 Aruba  ABW    1960 ABW-1960 54208  0.0 0.0  0.0 

데이터 프레임의 :

코드 : 내가 할 수있는 :

def topten(Year): 
    simple = df_details_merged.loc[Year].sort('MilExpend',ascending=False).reset_index() 
    simple = simple.drop(['Country Code', 'CountryYear'],axis=1).head(10) 
    simple.index = simple.index + 1 

    return simple 
    topten(1990) 

이 내가받은 오히려 큰 오류가있다 도움이 필요하십니까? 나는 심지어 그 실수가 무엇인지 알 수 없다. :-(

C:\Users\mycomputer\Anaconda3\lib\site-packages\ipykernel\__main__.py:2: FutureWarning: sort is deprecated, use sort_values(inplace=True) for INPLACE sorting 
    from ipykernel import kernelapp as app 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
C:\Users\mycomputer\Anaconda3\lib\site-packages\pandas\core\series.py in _try_kind_sort(arr) 
    1738     # if kind==mergesort, it can fail for object dtype 
-> 1739     return arr.argsort(kind=kind) 
    1740    except TypeError: 

TypeError: '<' not supported between instances of 'numpy.ndarray' and 'str' 

During handling of the above exception, another exception occurred: 

TypeError         Traceback (most recent call last) 
<ipython-input-105-0c974c6a1b44> in <module>() 
----> 1 topten(1990) 

<ipython-input-104-b8c336014d5b> in topten(Year) 
     1 def topten(Year): 
----> 2  simple = df_details_merged.loc[Year].sort('MilExpend',ascending=False).reset_index() 
     3  simple = simple.drop(['Country Code', 'CountryYear'],axis=1).head(10) 
     4  simple.index = simple.index + 1 
     5 

C:\Users\mycomputer\Anaconda3\lib\site-packages\pandas\core\series.py in sort(self, axis, ascending, kind, na_position, inplace) 
    1831 
    1832   return self.sort_values(ascending=ascending, kind=kind, 
-> 1833         na_position=na_position, inplace=inplace) 
    1834 
    1835  def order(self, na_last=None, ascending=True, kind='quicksort', 

C:\Users\mycomputer\Anaconda3\lib\site-packages\pandas\core\series.py in sort_values(self, axis, ascending, inplace, kind, na_position) 
    1751   idx = _default_index(len(self)) 
    1752 
-> 1753   argsorted = _try_kind_sort(arr[good]) 
    1754 
    1755   if not ascending: 

C:\Users\mycomputer\Anaconda3\lib\site-packages\pandas\core\series.py in _try_kind_sort(arr) 
    1741     # stable sort not available for object dtype 
    1742     # uses the argsort default quicksort 
-> 1743     return arr.argsort(kind='quicksort') 
    1744 
    1745   arr = self._values 

TypeError: '<' not supported between instances of 'numpy.ndarray' and 'str' 
+0

그것을입니다. 대신'sort_values'를 사용할 수 있습니까?'sort'는 더 이상 사용되지 않습니다 – Denziloe

+0

@ Denziloe 나는 그것을 변경하고 또 다른 오류가 있습니다. 글자 수 제한의 전체 오류 bc를 포함 할 수는 없지만 마지막 줄은 ValueError입니다 : 객체 유형 에 대해 MilExpend라는 축이 없음> –

+0

'df_details_merged.loc [Year]'가 무엇인지 확인하십시오. . 분명히 그것은 하나의 열만 있기 때문에 sort_values에 열 인수를 사용하지 않는 Series입니다. – Denziloe

답변

1

.loc에 첫 번째 인수는 라벨입니다.

당신이 df_details_merged.loc[1960]를 호출 할 때, 팬더 레이블 1960와 행을 찾아 일련의 해당 행을 반환합니다. 당신이 그래서 값이 해당 행의 값을 인으로, 인덱스 Country Name, Country Code, ...으로 시리즈를 다시 얻을. 그런 다음 코드는 MilExpend하여 정렬 시도하고 실패 곳이다.

당신이 loc 아니다 필요하지만, 시뮬레이션은 무엇 조건 : df[df.Year == Year]. 즉, "전체"데이터 프레임을 제공하지만 "Year"변수에 지정된 연도 (예 : 1960)가 포함 된 위치 만 입력하십시오 (0120). . 사용되지되고, 그래서 함께 퍼팅 대신 sort_values를 사용 : 당신이 지금하고있는대로

simple = df_details_merged[df_details_merged.Year == Year].sort_values(by='MilExpend', ascending=False).reset_index()

그런 다음 당신이 가서 열을 삭제하고 상위 10 행을 가져올 수

+0

@stephan 감사합니다! 좋은 소식은 오류가 없다는 것이 었습니다. 나는 topten (1980)에 넣었을 때 기둥이 제시 되었으나 나중에는 데이터가 표시되지 않았습니다. 무슨 일이 있었는지 아십니까? 도와 줘서 고마워. –

+0

데이터를 보지 않고 말하기는 어렵지만, 어떤 이유로 든 DataFrame에서 조건 (연도 == 1980)과 일치하는 것으로 들립니다. 따라서 함수를 실행하기 전에 데이터를주의 깊게 검사해볼 가치가 있습니다. 대화 형 셸에서'df [df.Year == 1980]'를 실행하고 행이 반환되는지 확인하십시오. 1) – Stephan

+0

죄송합니다. @ 스탄 .... 가족 문제가 발생했습니다. 나는 당신의 제안을 할 때만 여전히 칼럼을 얻었다. 아마 오프라인으로 이메일을 보낼 수 있습니까? –