Write a Python function rainaverage(l)  | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Write a Python function rainaverage(l) 

Write a Python function rainaverage(l) that takes as input a list of rainfall recordings and computes the avarage rainfall for each city. The output should be a list of pairs (c,ar)where c is the city and ar is the average rainfall for this city among the recordings in the input list. Note that arshould be of type float. The output should be sorted in dictionary order with respect to the city name. Here are some examples to show how rainaverage(l) should work. >>> rainaverage([(1,2),(1,3),(2,3),(1,1),(3,8)]) [(1, 2.0), (2, 3.0), (3, 8.0)] >>> rainaverage([('Bombay',848),('Madras',103),('Bombay',923),('Bangalore',201),('Madras',128)]) [('Bangalore', 201.0), ('Bombay', 885.5), ('Madras', 115.5)] I tried this, but it didn't work. I'm struck up import pandas as pd def l = [('Bombay',848),('Madras',103),('Bombay',923),('Bangalore',201),('Madras',128)] df = pd.DataFrame(l, columns=['city', 'rainfall']) output = [] for c in df['city'].unique(): output += [(c, df[df['city'] == c]['rainfall'].mean())] print(output)

20th Feb 2019, 12:19 PM
Roshini Manoharan
6 Answers
+ 5
I think you are really close, as all you need to implement is a .sort method on the output and wrap it into a function. Check out the code below, it checks the validity of the mean calculation by utilizing pandas' groupby method: https://code.sololearn.com/ckY2wAq7BeG0/?ref=app
20th Feb 2019, 8:32 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
In Sololearn indeed, no module is named pandas ;) But the code should work on any environment having pandas installed.
21st Feb 2019, 3:56 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
Is there any other way other than pandas?
22nd Feb 2019, 2:09 AM
Roshini Manoharan
0
Of course. You can use simple lists of tuples (key, value) iterate through them and (for example) create new lists with [0] element as "key" and all others [1:] appended as discrete values -- then just display a[0], mean(a[1:]) In your case it would result in: ['Madras', 103, 128], ['Bombay', 848, 923], ['Bangalore', 201]
22nd Feb 2019, 8:02 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
@roshini manoharan require for nptel it seems #XD
26th Feb 2019, 3:29 PM
Niladri Bit
Niladri Bit - avatar
- 1
Hey but it says there is no module named pandas!
21st Feb 2019, 12:15 PM
Roshini Manoharan