madman
madman

Reputation: 153

Simple Pandas issue, Python

I want to import a txt file, and do a few basic actions on it.

For some reason I keep getting an unhashable type error, not sure what the issue is:

def loadAndPrepData(filepath):

    import pandas as pd 
    pd.set_option('display.width',200)

    dataFrame = pd.read_csv(filepath,header=0,sep='\t') #set header to first row and sep by tab
    df = dataFrame[0:639,:]
    print df 

filepath = 'United States Cancer Statistics, 1999-2011 Incidencet.txt' 

loadAndPrepData(filepath)

Traceback:

Traceback (most recent call last):
  File "C:\Users\Michael\workspace\UCIIntrotoPythonDA\src\Michael_Madani_week3.py", line 16, in <module>
    loadAndPrepData(filepath)
  File "C:\Users\Michael\workspace\UCIIntrotoPythonDA\src\Michael_Madani_week3.py", line 12, in loadAndPrepData
    df = dataFrame[0:639,:]
  File "C:\Users\Michael\Anaconda\lib\site-packages\pandas\core\frame.py", line 1797, in __getitem__
    return self._getitem_column(key)
  File "C:\Users\Michael\Anaconda\lib\site-packages\pandas\core\frame.py", line 1804, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Users\Michael\Anaconda\lib\site-packages\pandas\core\generic.py", line 1082, in _get_item_cache
    res = cache.get(item)
TypeError: unhashable type

Upvotes: 1

Views: 316

Answers (1)

firelynx
firelynx

Reputation: 32214

The problem is that using the item getter ([]) needs hashable types. When you provide it with [:] this is fine, but when you provide it with [:,:], you will get this error.

pd.DataFrame({"foo":range(1,10)})[:,:]

TypeError: unhashable type

While this works just fine:

pd.DataFrame({"foo":range(1,10)})[:]

However, you should be using .loc no matter how you want to slice.

pd.DataFrame({"foo":range(1,10)}).loc[:,:]
   foo
0    1
1    2
2    3
3    4
4    5
5    6
6    7
7    8
8    9

Upvotes: 1

Related Questions