Error: pandas hashtable keyerror

后端 未结 3 1107
温柔的废话
温柔的废话 2020-11-22 01:00

I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code w

3条回答
  •  独厮守ぢ
    2020-11-22 01:39

    I think first is best investigate, what are real columns names, if convert to list better are seen some whitespaces or similar:

    print (reviews_new.columns.tolist())
    

    I think there can be 2 problems (obviously):

    1.whitespaces in columns names (maybe in data also)

    Solutions are strip whitespaces in column names:

    reviews_new.columns = reviews_new.columns.str.strip()
    

    Or add parameter skipinitialspace to read_csv:

    reviews_new = pd.read_csv("D:\\aviva.csv", skipinitialspace=True)
    

    2.different separator as default ,

    Solution is add parameter sep:

    #sep is ;
    reviews_new = pd.read_csv("D:\\aviva.csv", sep=';')
    #sep is whitespace
    reviews_new = pd.read_csv("D:\\aviva.csv", sep='\s+')
    reviews_new = pd.read_csv("D:\\aviva.csv", delim_whitespace=True)
    

    EDIT:

    You get whitespace in column name, so need 1.solutions:

    print (reviews_new.columns.tolist())
    ['Name', ' Date', ' review'] 
              ^        ^
    

提交回复
热议问题