删除.csv文件中的逗号时出现关键错误

时间:2018-09-08 09:39:39

标签: python pandas

数据:Github_Link

数据框如下所示: enter image description here

我正在尝试删除第一行中的逗号(有些内容类似于“ 1,000”)

但有一个关键错误:“价格”

代码:

import pandas

def main():
    df=pandas.read_csv("Rent_Message.csv",index_col=0)
    df=df.drop(df.columns[df.columns.str.contains('Unnamed',case = False)],axis = 1)
    df['Price'] = df['Price'].str.replace(",").astype(float)
main()

2 个答案:

答案 0 :(得分:2)

这是因为在替换字符串之前,您将该列作为索引。另外,您不会用逗号替换逗号,因为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   

答案 1 :(得分:2)

如d_kennetz所指出,Price是您的索引列。您可以按照他的方法在以后设置索引,也可以使用此代码段代替索引值

df.index = df.index.str.replace(",","").astype(float)