Pandas数据框中不可哈希类型错误

15

我有以下的pandas数据框:

df.shape

(86, 245)

然而,当我这样做时:

df[0, :]

我遇到了错误:

*** TypeError: unhashable type

我该怎么修复这个问题?我只想获取第一行。


你能展示一下如何构建 df 吗?现在我们只能猜测发生了什么。 - Willem Van Onsem
2个回答

16
如果需要将第一行作为 Series,只需使用 DataFrame.iloc
df.iloc[0, :]

如果需要使用 DataFrame,则需要使用 iloc,但要添加 [] 或使用 head

df.iloc[[0], :]
df.head(1)

示例:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

print (df.iloc[0, :])
A    1
B    4
C    7
D    1
E    5
F    7
Name: 0, dtype: int64

print (df.head(1))
   A  B  C  D  E  F
0  1  4  7  1  5  7

print (df.iloc[[0], :])
   A  B  C  D  E  F
0  1  4  7  1  5  7

8

在尝试对 ps.Dataframe 使用.loc函数时,我遇到了一个TypeError:unhashable type: 'Series'错误。

我的错误是使用了.loc(...),而应该使用.loc[...]

错误示例:

import pandas as pd

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)

# typical mistake
print(df.loc(
    df["A"] == 1
))

结果:

PS C:\Users\rascoussier\python\stackoverflow\type_error_with_df_loc> C:\Users\rascoussier\Anaconda3\envs\elastic-1\python.exe .\main.py                                 
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3
Traceback (most recent call last):
  File "C:\Users\rascoussier\python\stackoverflow\type_error_with_df_loc\main.py", line 12, in <module>
    print(df.loc(
  File "C:\Users\rascoussier\Anaconda3\envs\elastic-1\lib\site-packages\pandas\core\indexing.py", line 634, in __call__
    axis = self.obj._get_axis_number(axis)
  File "C:\Users\rascoussier\Anaconda3\envs\elastic-1\lib\site-packages\pandas\core\generic.py", line 550, in _get_axis_number
    return cls._AXIS_TO_AXIS_NUMBER[axis]
TypeError: unhashable type: 'Series'

在 VSCode 上,Pylance 没有检测到这个错误。我不知道为什么。但以下是更正方式。

import pandas as pd

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)

# correction
print("Correction works, see below: ")
print(df.loc[
    df["A"] == 1
])

结果:

PS C:\Users\rascoussier\python\stackoverflow\type_error_with_df_loc> C:\Users\rascoussier\Anaconda3\envs\elastic-1\python.exe .\main.py
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3
Correction works, see below:
   A  B  C  D  E  F
0  1  4  7  1  5  7

备注:我的示例与问题要求的略有不同,但由于我在搜索时找到了这个解决方案,它可能会帮助其他遇到相同问题的人。


2
谢谢!这种情况经常发生在我身上,但总有那么一个早晨我没有注意到它... - Stefano
我的错误是忘记了“.loc”(应该是“df.loc[series, 'a']”,而不是“df[series,'a']”)... - mikm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接