-1
\$\begingroup\$

I have a dataframe where i want to obtain the appropriate levels. I successively check each resolution range until the lowest hits.

Seems a bit iffy to me, is there a better way to put this?

data = pd.DataFrame(some data)
resolutions = [0.1, 0.2, 0.5, 1, 1.5, 2, 3, 5, 10, 
               15, 20, 30, 40, 50, 60, 70, 80]
    
max_of_Z = data['Z'].max()

if (max_of_Z == 0):
    print ('no rainfall')
    levels = np.arange(min, min + (0.1 * 12), 0.1)    
else:
    hit = False
    for res in resolutions:
        condition = res*12
        if condition > data['Z'].max():
            print("Using {}".format(res))
            levels = np.arange(min_val, max_val + condition, res)
            hit = True
            break
    if not hit:
        res = 90
        print("Using {}".format(res))
        condition = res*12
        levels = np.arange(min_val, max_val + condition, res)
\$\endgroup\$
2
  • 6
    \$\begingroup\$ Please edit your question so that the title describes the purpose of the code, rather than its mechanism. We really need to understand the motivational context to give good reviews. Thanks! \$\endgroup\$ Nov 23 at 7:14
  • 3
    \$\begingroup\$ We also need a complete example. Could you give us some data that we can use? \$\endgroup\$
    – Teepeemm
    Nov 23 at 19:21
0
\$\begingroup\$

Document the purpose of "everything" in a program, at least everything public.
This starts with giving things like literals (what is 12 or 90?) or a bunch of statements a name; Python convention for internal is to start the name with an underscore.
Use names (and "expressions factored out") consistently - min_val may not be the greatest of names (compare to, say, min_Z or even min_of_Z), but you use min (deprecated for being the name of a built-in) in the same context.
data['Z'].max() is repeated after first use of max_of_Z.

Use a tuple for a sequence that shall stay as initialised - resolutions looks the type.

Don't open code what you feel/know to be in the library.

from bisect import bisect_right

resolutions = (0.1, 0.2, 0.5, 1, 1.5, 2, 3, 5, 10, 
               15, 20, 30, 40, 50, 60, 70, 80, 90)
    
max_of_Z = data['Z'].max()

def _levels(maximum):
    """ Return values from min_val to above max_val 
        spaced by a step derived from maximum. 
        Prints something. """
    above = min(bisect_right(resolutions, maximum), len(resolutions) - 1)
    resolution = resolutions[above]
    
    if (maximum == 0):
        print('no rainfall')
    else:
        print("Using", resolution)
    excess = 12
    condition = resolution * excess
    return np.arange(min_val, max_val + condition, resolution)

levels = _levels(max_of_Z)
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.