【问题标题】:Trying to remove commas and dollars signs with Pandas in Python尝试在 Python 中使用 Pandas 删除逗号和美元符号
【发布时间】:2016-11-25 18:27:41
【问题描述】:

删除列中的逗号和美元符号。但是当我这样做时,表格会将它们打印出来并且仍然在那里。是否有其他方法可以使用 pandas 函数删除命令和美元符号。我无法在 API Docs 中找到任何内容,或者我找错了地方

 import pandas as pd
    import pandas_datareader.data as web

players = pd.read_html('http://www.usatoday.com/sports/mlb/salaries/2013/player/p/')


df1 = pd.DataFrame(players[0])


df1.drop(df1.columns[[0,3,4, 5, 6]], axis=1, inplace=True)
df1.columns = ['Player', 'Team', 'Avg_Annual']
df1['Avg_Annual'] = df1['Avg_Annual'].replace(',', '')

print (df1.head(10))

【问题讨论】:

  • 只需在替换中添加 regex=True 即可。

标签: python pandas


【解决方案1】:

您必须根据http://pandas.pydata.org/pandas-docs/stable/text.html 访问str 属性

df1['Avg_Annual'] = df1['Avg_Annual'].str.replace(',', '')
df1['Avg_Annual'] = df1['Avg_Annual'].str.replace('$', '')
df1['Avg_Annual'] = df1['Avg_Annual'].astype(int)

交替;

df1['Avg_Annual'] = df1['Avg_Annual'].str.replace(',', '').str.replace('$', '').astype(int)

如果您想优先考虑打字时间而不是可读性。

【讨论】:

    【解决方案2】:

    @bernie 的回答非常适合您的问题。这是我对在 pandas 中加载数值数据的一般问题的看法。

    数据的来源通常是为直接消费而生成的报告。因此存在额外的格式,如%、千位分隔符、货币符号等。所有这些对于阅读都很有用,但会导致默认解析器出现问题。我的解决方案是将列类型转换为字符串,一一替换这些符号,然后将其转换回适当的数字格式。拥有一个只保留[0-9.] 的样板函数很诱人,但会导致千位分隔符和小数点被交换的问题,在科学记数法的情况下也是如此。这是我的代码,我将其包装到一个函数中并根据需要应用。

    df[col] = df[col].astype(str)  # cast to string
    
    # all the string surgery goes in here
    df[col] = df[col].replace('$', '')
    df[col] = df[col].replace(',', '')  # assuming ',' is the thousand's separator in your locale
    df[col] = df[col].replace('%', '')
    
    df[col] = df[col].astype(float)  # cast back to appropriate type
    

    【讨论】:

    • @FaheemMitha,如果您需要一些帮助,您必须更具体地说明您的用例
    【解决方案3】:

    无耻地从this answer盗取... 但是,这个答案只是改变一个字符,并没有完成酷炫:因为它需要一本字典,你可以替换任意数量的字符一次,以及在任意数量的列中。

    # if you want to operate on multiple columns, put them in a list like so:
    cols = ['col1', 'col2', ..., 'colN']
    
    # pass them to df.replace(), specifying each char and it's replacement:
    df[cols] = df[cols].replace({'\$': '', ',': ''}, regex=True)
    

    @shivsn 发现你需要使用regex=True;您已经知道替换(但也没有显示尝试在多个列上或同时在美元符号和逗号上使用它)。

    这个答案只是在一个地方为像我这样的人拼出我从其他人那里找到的详细信息(例如,pythonpandas 的新手)。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 2017-08-23
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2018-06-19
      相关资源
      最近更新 更多