Why we need to use str accessor?

Hi!
It is said in exersise:
With series, however, we use the str accessor followed by [ ] (brackets) to access the elements in each list in the series:

laptops[“gpu”].str.split().str[0]

Wy we need to use exactly Series.str (.str[0]) accessor at the end of the code?

As i understand Series.str accessor was desined to access a string (string type objects), but in our case it access the first element of each list:

  • laptops[“gpu”].str.split()[0]
  • laptops[“gpu”].str.split()[1]
  • laptops[“gpu”].str.split()[2]
  • laptops[“gpu”].str.split()[1302]

Well, Series.str enables us to access vectorized string operations. I like to look at it like this; Series.str.split() splits entries in a column by whitspaces (it does this to multiple rows in the column at once), hence to continue operating on the vectorized result, we use .str to select the result in a vectorized manner as opposed to .str.split()[0] which is not a vectorized operation.

2 Likes

Hey @7933509 , you need to use the Series.str[index_number] to get the exact value you want from your dataFrame, and note this is just a pandas specification . To retrieve a value for a list using normal python, you only need to do List[index_number].

Also, note that laptops[‘gpu’].str.split()[0] does not only retrieve the first element in your dataFrame, it also splits the value with spaces in between.

Check out this mission on dataquest for better understanding, if you still need better understanding you can let me known.

Happy learning!!

2 Likes