Replacing Python list comprehension with pandas series

Viewed 59

It happens quite a lot that I want to create a list of function values, say, [f(0), f(2),... f(100)], and then plot the result. My go-to solution has been something like

x = list(range(101))
y = [f(n) for n in x]
plt.plot(x,y)

However, I am using pandas for most other stuff, and I was wondering if there is a neater way to do the same thing with pandas? It is possible to do something like

x = pd.Series(range(101))
y = x.apply(f)
y.plot()

but I feel awkward defining x like this. Is there a cleaner way?

1 Answers

dont do this ... instead convert f to accept a pandas series

def f(x):
    return numpy.sin(x) + 3

x = pd.Series(range(101))
y = f(x)

series.apply is largely just a convenience function, it likely will not provide any speedup

if you just want range... just use numpy.arange it should perform as well as or better than a series at the next step

x = np.arange(101)
y = f(x)

and if you dont care about x later you can just pass arange directly

y = f(np.arange(101))
plt.plot(y)
plt.show()
Related