There's more...

The function wide_to_long works when all groupings of variables have the same numeric ending like they did in this recipe. When your variables do not have the same ending or don't end in a digit, you can still use wide_to_long to do simultaneous column stacking. For instance, let's take a look at the following dataset:

>>> df = pd.read_csv('data/stackme.csv')
>>> df

Let's say we wanted columns a1 and b1 stacked together, as well as columns d and e. Additionally, we wanted to use a1 and b1 as labels for the rows. To accomplish this task, we would need to rename the columns so that they ended in the label we desired:

>>> df2 = df.rename(columns = {'a1':'group1_a1', 'b2':'group1_b2',
'd':'group2_a1', 'e':'group2_b2'})
>>> df2

We would then need to modify the suffix parameter, which normally defaults to a regular expression that selects digits. Here, we simply tell it to find any number of characters:

>>> pd.wide_to_long(df2, 
stubnames=['group1', 'group2'],
i=['State', 'Country', 'Test'],
j='Label',
suffix='.+',
sep='_')
..................Content has been hidden....................

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