Python 删除.csv文件中的逗号时出现关键错误
数据: 数据帧如下所示: 我正在尝试删除第一行中的逗号(有些东西像“1000”) 但有一个关键错误:“价格” 代码:Python 删除.csv文件中的逗号时出现关键错误,python,pandas,Python,Pandas,数据: 数据帧如下所示: 我正在尝试删除第一行中的逗号(有些东西像“1000”) 但有一个关键错误:“价格” 代码: 这是因为在替换字符串之前,您将该列作为索引。另外,您没有用任何东西替换逗号,因为str.replace接受2个参数,最后返回df import pandas as pd def main(): df = pd.read_csv("Rent_message.csv") # don't set index, you can do it later. df = df
这是因为在替换字符串之前,您将该列作为索引。另外,您没有用任何东西替换逗号,因为str.replace接受2个参数,最后返回df
import pandas as pd
def main():
df = pd.read_csv("Rent_message.csv") # don't set index, you can do it later.
df = df.drop(df.columns[df.columns.str.contains('Unnamed',case = False)],axis = 1) # this line is okay
df['Price'] = df['Price'].str.replace(",", '').astype(float) # fix str.replace
df.set_index('Price', inplace=True)
return df
main()
输出:
df.head()
Postcode Type_Property Num_Bedroom Num_Bathroom Num_Carspace \
Price
550.0 8/2/1916 house 4 2 2
350.0 7/1/1916 house 3 1 5
450.0 11/6/1916 house 4 2 2
300.0 7/10/1916 house 4 2 2
400.0 7/30/1916 house 4 1 2
300.0 7/1/1916 unit 2 1 2
200.0 6017 apartment 2 1 1
950.0 6004 apartment 3 2 2
1500.0 6151 apartment 4 3 1
这是因为在替换字符串之前,您将该列作为索引。另外,您没有用任何东西替换逗号,因为str.replace接受2个参数,最后返回df
import pandas as pd
def main():
df = pd.read_csv("Rent_message.csv") # don't set index, you can do it later.
df = df.drop(df.columns[df.columns.str.contains('Unnamed',case = False)],axis = 1) # this line is okay
df['Price'] = df['Price'].str.replace(",", '').astype(float) # fix str.replace
df.set_index('Price', inplace=True)
return df
main()
输出:
df.head()
Postcode Type_Property Num_Bedroom Num_Bathroom Num_Carspace \
Price
550.0 8/2/1916 house 4 2 2
350.0 7/1/1916 house 3 1 5
450.0 11/6/1916 house 4 2 2
300.0 7/10/1916 house 4 2 2
400.0 7/30/1916 house 4 1 2
300.0 7/1/1916 unit 2 1 2
200.0 6017 apartment 2 1 1
950.0 6004 apartment 3 2 2
1500.0 6151 apartment 4 3 1
正如d_kennetz所指出的,
Price
是您的索引列。您可以按照他的方法在稍后阶段设置索引,也可以使用此代码段替换索引值
df.index = df.index.str.replace(",","").astype(float)
正如d_kennetz所指出的,
Price
是您的索引列。您可以按照他的方法在稍后阶段设置索引,也可以使用此代码段替换索引值
df.index = df.index.str.replace(",","").astype(float)
请包括完整的回溯CSV文件的内容是什么?@kampangala,在他们的链接中,尽管最好在问题中包含一些代表性的数据。OP:请同时显示
print(df.columns)
的输出,您是否已正确检查其是否为key error或TypeError。我能找出的一个错误是relplace函数至少需要两个参数,而您已经给出了一个。请包括完整的回溯CSV文件的内容是什么?@kampangala,在他们的链接中,尽管最好在问题中包含一些代表性的数据。OP:请同时显示print(df.columns)
的输出,您是否已正确检查其是否为key error或TypeError。我能找出的一个错误是relplace函数至少需要两个参数,而您已经给出了一个。df['Price']=df['Price'].str.replace(“,”,”).astype(float)#fix str.replace replace中应该有一个逗号,这是一个小问题^ ^很好的回答!抱歉,这就是我重新键入代码而不是仅仅粘贴代码所得到的结果:P,我编辑了答案以包含逗号。df['Price']=df['Price'].str.replace(“,”,”)。astype(float)#fix str.replace中应该有一个逗号,一个小问题^ ^很好!很抱歉,这就是我重新键入代码而不是仅仅粘贴代码得到的结果:P,我编辑了答案以包含逗号。