What is the difference between pandas' df.take() and df.iloc[]?

Viewed 398

To me, it seems df.take() has the same functionality as the more common df.iloc[]. I've checked the documentation but couldn't find a difference. Are there cases where take() is preferable to iloc[]?

2 Answers

There are some pretty important differences:

  1. .iloc is of type <class 'pandas.core.indexing._iLocIndexer'>, whereas .take is a method
  2. Most important .iloc can index into rows AND columns at the same time. .take can only select from one or the other.
  3. .take always returns a DataFrame with the same number of levels in both axes. In contrast, .iloc can easily return fewer levels, to the point of totally returning a Series instead of a DataFrame, i.e. df.iloc[3, :] returns a Series with the columns as the index, but df.take([3]) returns a DataFrame with only one row.
  4. Also pretty important, .take always returns a copy. This means that you can also use .iloc for assignment, but this is not the case for .take.

Case: I received the following error message and finally figured out that it was hanging up on the .iloc.

TypeError: unhashable type: 'list'

Since the iloc returned a list which is mutable, the code wouldn't proceed with the summation. A simple change from .iloc to .take fixed the problem.

#returns list
df3['sum_total']= df3.iloc[:,-30].sum(axis=[1])
#returns tuple and worked
df3['sum_total']= df3.take([-30], axis=1).sum(axis=1)
Related