Home > other >  Pandas in the groupby and the collocation of the apply function is used (statement execution error)
Pandas in the groupby and the collocation of the apply function is used (statement execution error)

Time:10-02

The existing list of top cities, a group of 2019 national GDP contains the serial number, provinces, cities, GDP ($one hundred million) in four fields, need to find the third rank among each province city,
Rules are as follows: if it is a municipality directly under the central government, and the municipalities directly under the central government is GDP100 is strong, the output of the municipality directly under the central government records; If not municipality directly under the central government, and can't find the third within 100, output 'results cannot be found; Find the third, the output of the third city record
My code is like this:
 GDP_Data_2019=pd. Read_excel (' D: \ \ \ \ python learning netease micro data analysis curriculum based \ \ \ \ python data analysis in 2019 GDP ranking top 100 cities. XLSX ') 
Def top_3 (x) :
If x [' provinces'] the isin ([' Shanghai ', 'Beijing', 'tianjin', 'chongqing']) :
Return the x
Elif len (x) & lt;=2:
Return 'no such results'
The else:
Return x.i loc [2, :)
Result=GDP_Data_2019. Groupby ([' provinces']) [[' cities', 'GDP (one hundred million yuan)]]. Apply (top_3)
The result

Running result=GDP_Data_2019. Groupby ([' provinces']) [[' cities', 'GDP (one hundred million yuan)]]. Apply (top_3) this sentence error KeyError:' provinces'
Has carried on the debugging then I found that if run GDP_Data_2019. Groupby ([' provinces']), but not an error, the running result.=GDP_Data_2019 groupby ([' provinces']) agg ({' GDP (one hundred million yuan) ':' mean '}) is still not an error, show the fields in the code and data sheet is to be able to match, don't know where it's because of the now, bosses guidance, thank you ~ ~ ~
  • Related