2

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
  • 1
    What's awkward about this? What is it that you are trying to avoid? Commented Jun 22, 2020 at 0:42

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

2 Comments

or without pandas y=list(map(f, x))
@ansev the OP already has a perfectly good approach for doing this without pandas... The whole point of the question is to use pandas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.