3

i have a pandas series like this:

0          $233.94
1          $214.14
2          $208.74
3          $232.14
4          $187.15
5          $262.73
6          $176.35
7          $266.33
8          $174.55
9          $221.34
10         $199.74
11         $228.54
12         $228.54
13         $196.15
14         $269.93
15         $257.33
16         $246.53
17         $226.74

i want to get rid of the dollar sign so i can convert the values to numeric. I made a function in order to do this:

def strip_dollar(series):
    for number in dollar:
        if number[0] == '$':
            number[0].replace('$', ' ')

    return dollar

This function is returning the original series untouched, nothing changes, and i don't know why.

Any ideas about how to get this right?

Thanks in advance

3
  • 3
    df['col'].str.replace("$", "") ? Commented Jul 3, 2018 at 12:21
  • 1
    nonono :). You shuld use pd.to_numeric() but replace $ first. Commented Jul 3, 2018 at 12:22
  • 1
    replace is String function so first you should convert the values to string and then you replace Commented Jul 3, 2018 at 12:28

3 Answers 3

6

Use lstrip and convert to floats:

s = s.str.lstrip('$').astype(float)
print (s)
0     233.94
1     214.14
2     208.74
3     232.14
4     187.15
5     262.73
6     176.35
7     266.33
8     174.55
9     221.34
10    199.74
11    228.54
12    228.54
13    196.15
14    269.93
15    257.33
16    246.53
17    226.74
Name: A, dtype: float64

Setup:

s = pd.Series(['$233.94', '$214.14', '$208.74', '$232.14', '$187.15', '$262.73', '$176.35', '$266.33', '$174.55', '$221.34', '$199.74', '$228.54', '$228.54', '$196.15', '$269.93', '$257.33', '$246.53', '$226.74'])
print (s)
0     $233.94
1     $214.14
2     $208.74
3     $232.14
4     $187.15
5     $262.73
6     $176.35
7     $266.33
8     $174.55
9     $221.34
10    $199.74
11    $228.54
12    $228.54
13    $196.15
14    $269.93
15    $257.33
16    $246.53
17    $226.74
dtype: object
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot for your help @jezrael. I marked this answer as correct because i didn't know the lstrip method. Nice and clever. Thanks!! :)
2

Using str.replace("$", "")

Ex:

import pandas as pd
df = pd.DataFrame({"Col" : ["$233.94", "$214.14"]})
df["Col"] = pd.to_numeric(df["Col"].str.replace("$", ""))
print(df) 

Output:

      Col
0  233.94
1  214.14

Comments

2

CODE:

ser = pd.Series(data=['$123', '$234', '$232', '$6767'])
def rmDollar(x):
    return x[1:]
serWithoutDollar = ser.apply(rmDollar)
serWithoutDollar

OUTPUT:

0     123
1     234
2     232
3    6767
dtype: object

Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.