How it works...

The wide_to_long function works in a fairly specific manner. Its main parameter is stubnames, which is a list of strings. Each string represents a single column grouping. All columns that begin with this string will be stacked into a single column. In this recipe, there are two groups of columns: actor, and actor_facebook_likes. By default, each of these groups of columns will need to end in a digit. This digit will subsequently be used to label the reshaped data. Each of these column groups has an underscore character separating the stubname from the ending digit. To account for this, you must use the sep parameter.

The original column names do not match the pattern needed for wide_to_long to work. The column names could have been changed manually by exactly specifying their values with a list. This could quickly become a lot of typing so instead, we define a function that automatically converts our columns to a format that works. The change_col_name function removes _name from the actor columns and rearranges the Facebook columns so that now they both end in digits.

To actually accomplish the column renaming, we use the rename method in step 2. It accepts many different types of arguments, one of which is a function. When passing it to a function, every column name gets implicitly passed to it one at a time.

We have now correctly created two independent groups of columns, those beginning with actor and actor_facebook_likes that will be stacked. In addition to this, wide_to_long requires a unique column, parameter i, to act as an identification variable that will not be stacked. Also required is the parameter j, which simply renames the identifying digit stripped from the end of the original column names. By default, the prefix parameter contains the regular expression, d+ that searches for one more or more digits. The d is a special token that matches the digits 0-9. The plus sign, +, makes the expression match for one or more of these digits.

To become a powerful user of the str methods, you will need to be familiar with regular expressions, which are a sequence of characters that match a particular pattern within some text. They consist of metacharacters, which have a special meaning, and literal characters. To make yourself useful with regular expressions check this short tutorial from Regular-Expressions.info (http://bit.ly/2wiWPbz).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.59