试图用Python中的Pandas删除逗号和美元符号

Mar*_*ark 23 python pandas

请从列中删除逗号和美元符号.但是当我这样做时,桌子将它们打印出来并且仍然存在于那里.有没有不同的方法来使用熊猫功能删除commans和美元符号.我无法在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))
Run Code Online (Sandbox Code Playgroud)

ber*_*nie 57

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

df1['Avg_Annual'] = df1['Avg_Annual'].str.replace(',', '')
df1['Avg_Annual'] = df1['Avg_Annual'].str.replace('$', '')
df1['Avg_Annual'] = df1['Avg_Annual'].astype(int)
Run Code Online (Sandbox Code Playgroud)


Hen*_*ndy 13

这个答案中无耻地偷走了... 但是,答案只是关于改变一个角色并且没有完成酷感:因为它需要一个字典,你可以一次替换任意数量的字符,以及任意数量的列.

# 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)
Run Code Online (Sandbox Code Playgroud)

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

这个答案很简单拼写出我从其他人发现在一个地方为那些像我一样的细节(例如菜鸟到pythonpandas).希望它有用.


BiG*_*YaN 5

@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
Run Code Online (Sandbox Code Playgroud)