简体   繁体   中英

Pandas handle negative value when doing operations such as sum()

I am looking for a way to convert my Revenue column from object to numeric but still keep negative values as I am trying to do the operation below

df

customerId  Revenue
3443        1,323.90
4325        -442
5833        -101
9424        1,539.20
df.types:
customer_ID: int 
Revenue: object
df['Revenue'].sum()

This is what I have tried so far but did not work: this simply converts negative values to positive

df["Revenue"] = pd.to_numeric(df["Revenue"].str.strip().str.replace(",", "")).abs()

Try via strip() , replace() and astype() method:

df['Revenue']=df['Revenue'].str.strip().str.replace(',','').astype(float)

OR

via strip() , replace() and to_numeric() method:

df['Revenue']=pd.to_numeric(df['Revenue'].str.strip().str.replace(',',''),errors='coerce')

You can do something like this -

>>> import pandas as pd
>>> 
>>> d = {
... 
...   'customer_id':[3443,4325,5833,9424]
...   ,'Revenue':['1,323.90',-442,-101,'1,539.20']
... }
>>> 
>>> df = pd.DataFrame(d)
>>> 
>>> 
>>> df['Revenue']=df.loc[:,'Revenue'].apply(lambda x: str(x).replace(',','')).astype(float)
>>> df
   customer_id  Revenue
0         3443   1323.9
1         4325   -442.0
2         5833   -101.0
3         9424   1539.2
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM