NimbleTortoise
NimbleTortoise

Reputation: 365

What's the difference between using pd.Index vs explicit lists when creating a Series?

For instance:

pd.Series([1,2,3], index = ['a','b','c']) 

vs

pd.Series([1,2,3], index = pd.Index(['a','b','c']) 

When is it appropriate to use one over the other?

Upvotes: 0

Views: 420

Answers (1)

cs95
cs95

Reputation: 402313

It does not matter. The index argument accepts any list-like sequence. Regardless of what is passed, the Series constructor internally calls the ensure_index function in core/indexes/base.pyto convert the data to a Series. This function validates the passed index and constructs a pd.Index object.

If you pass a pd.Index object yourself, ensure_index may be able to exit early. Otherwise, it will have to create one from scratch. So there are minor performance benefits, but I would say the gains are at the "seriously, don't worry about it" level.

Idiomatically, all you need do is pass a list (as the simplest option) unless you have good reason to do so otherwise.

Upvotes: 1

Related Questions