Use this to ask technical questions NOT related to Dataquest courses - while doing any independent project or learning some other skill (even on another platforms!) or other such questions.
I’m having trouble understanding when to use the square brackets in a method statement and when to use just the parenthesis or both. I understand the square brackets refer to lists and column names. I also understand that parenthesis() are used for passing arguments. Here is an example of what I’m asking:
Both of these request the last value in a string. But WHEN should I use one or the other? In other words why is one enclosed with square and one enclosed with parens?
Do you know if there is a source explaining examples I can look up to help me memorize this? Maybe somewhere in the pandas documentation? All I need is a point in the right direction of where I may find the answer.
lets break these down:
“str” - this is a function turning what is in the brackets into a string
(element) - here the word element is being passed as an argument to the str function
.split - is a method being applied to our new string.
() - these parenthesis are just part of the .split method to allow for options to be passed
so, so far we have turned the word element into the string ‘element’ and then split it into a list:
[‘e’, ‘l’, ‘e’, ‘m’, ‘e’, ‘n’, ‘t’] and in the last part we use brackets to select the value of that list we want to return.
merged - I believe is the dataframe being used here
[‘CurrencyUnit’] - these brackets tell us that we are selecting the column named ‘CurrencyUnit’
.str - calls the string functions
.split() - is performing a vectorized split method on each value in the column that was selected
.str - calls the string functions again
.get - this is a method of that string function and requires an argument (i) to be passes
(-1) - this is the argument, the index number that the method requires
I think that generally in pandas, square brackets are used when you are selecting data, and () are used when you are doing stuff to that data. I’m still new here, so hopefully that helps and Im not steering you wrong