简体   繁体   中英

How can I do to remove $

Hello I have this file :

date;category_name;item_number;item_description;bottlevolume_ml;state_bottle_retail;bottles_sold;volume_sold_gallons
11/04/2015;APRICOT$ BRANDIES;54436;$Mr. Boston Apricot Brandy;750;6.75;12;2.38
03/02/2016;BLENDED WHISKIES;27605;Tin Cup;750;$20.63;2;0.40
02/11/2016;STRAIGHT BOURBON WHISKIES;19067;Jim Beam;1000;$18.89;24;6.34
02/03/2016;AMERICAN COCKTAILS;59154;1800 Ultimate Margarita;1750;$14.25;6;2.77
08/18/2015;VODKA 80 PROOF;35918;Five O'clock Vodka;1750;$10.80;12;5.55

I would like to remove the $ using panda.

I tried this :

import pandas as pd
import numpy as np
df = pd.read_csv('data2.csv', delimiter=';')

df.date = [x.strip('$') for x in df.date]
df.category_name = [x.strip('$') for x in df.category_name]
df.item_number = [x.strip('$') for x in df.ite_number]

But I would like using pandas to remove from all my columns the $

Any ideas ?

Thank you !

for c in df.select_dtypes('object').columns:
    df[c] = df[c].str.replace('$', '')

Explanation: If a column has a '$', it will be a object-type column. It's useful to select only these, because then you can use .str.replace ( https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html ) to find all '$"-signs in that column and replace it with an empty string.
Nothe that this solution also removes'$' in the middle of the string (in contrast to the .strip method you've used so far).

这应该工作。

df = df.apply(lambda x: x.str.strip('$') if x.dtype == "object" else x)

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