I am recreating a DataCamp exercise using Anaconda Jupyter Notebook and Python 3. The exercise is to import a csv file, create a new column with the value remaining after you use the .replace() method inside a lambda function to remove the dollar sign from the 'total_dollar' column. And then do the same thing again, into another new column, but this time using the RegEx.findall(). Where I run into trouble is using [0] to slice the re.findall() list to get just the value. DataCamp instructions say: Notice that because re.findall() returns a list, you have to slice it in order to access the actual value.
The following code gives me the correct answer on their web site, but not in Jupyter Notebook.
tips2 = pd.read_csv('c:\\datacamp\\data\\tips2.csv')
print(tips2.head())
# Write the lambda function using replace
tips2['total_dollar_replace'] = tips2.total_dollar.apply(lambda x: x.replace('$', ''))
# Write the lambda function using regular expressions
tips2['total_dollar_re'] = tips2.total_dollar.apply(lambda x: re.findall('\d+\.\d+', x)[0])
# Print the head of tips
print(tips2.head())
The output is the following:
total_bill tip sex smoker day time size total_dollar
0 16.99 1.01 Female No Sun Dinner 2.0 $16.99
1 10.34 1.66 Male No Sun Dinner 3.0 $10.34
2 21.01 3.50 Male No Sun Dinner 3.0 $21.01
3 23.68 3.31 Male No Sun Dinner 2.0 $23.68
4 24.59 3.61 Female No Sun Dinner 4.0 $24.59
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-152-598533768fa6> in <module>
28
29 # Write the lambda function using regular expressions
---> 30 tips2['total_dollar_re'] = tips2.total_dollar.apply(lambda x: re.findall('\d+\.\d+', x)[0])
31
32
C:\conda\envs\datacamp\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4036 else:
4037 values = self.astype(object).values
-> 4038 mapped = lib.map_infer(values, f, convert=convert_dtype)
4039
4040 if len(mapped) and isinstance(mapped[0], Series):
pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-152-598533768fa6> in <lambda>(x)
28
29 # Write the lambda function using regular expressions
---> 30 tips2['total_dollar_re'] = tips2.total_dollar.apply(lambda x: re.findall('\d+\.\d+', x)[0])
31
32
IndexError: list index out of range
Get rid of the index slicer and the output is better, but not exactly what it should be:
total_bill tip sex smoker day time size total_dollar \
0 16.99 1.01 Female No Sun Dinner 2.0 $16.99
1 10.34 1.66 Male No Sun Dinner 3.0 $10.34
2 21.01 3.50 Male No Sun Dinner 3.0 $21.01
3 23.68 3.31 Male No Sun Dinner 2.0 $23.68
4 24.59 3.61 Female No Sun Dinner 4.0 $24.59
total_dollar_replace total_dollar_re
0 16.99 [16.99]
1 10.34 [10.34]
2 21.01 [21.01]
3 23.68 [23.68]
4 24.59 [24.59]
The final column is not supposed to be a list of one, that was supposed to be the point of using the [0] slicer. Your help with understanding what I am missing is greatly appreciated.