2

I have a table with a column named 'Amount'. The cell values are mixture of numbers such as 1, 100, and 1000, and strings such as '(1000)' and '(999)' which indicates a negative value. How would I change the strings of negative values to numbers, like -1000 and -999? I don't know how to apply conditions on panda dataframes.

import pandas as pd
ws_actual = pd.read_excel(file_name, sheet_name=0)


Project Name    Amount
a   1000.53
b   (-100.2)
c   999.83
d   99999.1
e   333.62
f   (-10502.30)
g   (-2036.63)
h   25235
i   69103
j   5923
k   6920
5
  • post your sample data and your desired output Commented Sep 4, 2018 at 23:05
  • added a sample image Commented Sep 4, 2018 at 23:12
  • Post as text, not as an image Commented Sep 4, 2018 at 23:12
  • How can I save it as text and how to upload here? Commented Sep 4, 2018 at 23:15
  • I just copied and pasted the data in my question Commented Sep 4, 2018 at 23:16

1 Answer 1

1

Simply use strip. Although in your question, it is ambiguous if the values in parenthesis contain negative symbols or if the parenthesis need to be replaced with a negative symbol. If it is the latter you will need a regular expression here.

df.Amount.astype(str).str.strip('()').astype(float)

0      1000.53
1      -100.20
2       999.83
3     99999.10
4       333.62
5    -10502.30
6     -2036.63
7     25235.00
8     69103.00
9      5923.00
10     6920.00
Name: Amount, dtype: float64

If you have strings such as (1000) that also need to be converted to a negative number:

print(df)

  ProjectName  Amount
0           a  (1000)
1           b     100
2           c   (999)

df.Amount.astype(str).str.replace(r'\(([-\d\.]+)\)', r'-\1').astype(float)

0   -1000.0
1     100.0
2    -999.0
Name: Amount, dtype: float64
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot!! I put df.Amount.astype(str).strip('()').replace(',',"").astype(float) since I realized that there is a comma in (). When I run this code, I get an error saying that 'ValueError: could not convert string to float: '271,796.82''. I think I removed comma, but it was obviously not successful. Could you give a solution to this?
Use .str.replace instead of just .replace
Yay!!! It worked with astype(str).str.replace(',',"").str.replace(r'(([-\d\.]+))', r'-\1').astype(float) !!! Thank you !!!

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.