Error: pandas hashtable keyerror

后端 未结 3 1049
温柔的废话
温柔的废话 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:33
    dfObj['Hash Key'] = (dfObj['DEAL_ID'].map(str) +dfObj['COST_CODE'].map(str) +dfObj['TRADE_ID'].map(str)).apply(hash)
    
    #for index, row in dfObj.iterrows():
    #        dfObj.loc[`enter code here`index,'hash'] = hashlib.md5(str(row[['COST_CODE','TRADE_ID']].values)).hexdigest()
    
    print(dfObj['hash'])
    
    0 讨论(0)
  • 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'] 
              ^        ^
    
    0 讨论(0)
  • 2020-11-22 01:48
    import pandas as pd
    df=pd.read_csv("file.txt", skipinitialspace=True)
    df.head()
    df['review']
    
    0 讨论(0)
提交回复
热议问题