2017-09-18 251 views
2

串KeyError異常0 LOC選擇朋友送我這個僞代碼,爲了做一個簡單的暗號:與大熊貓

chaine1="abcdefghijklmnopqrstuvwxyz" 
chaine2="abcdefghijklmnopqrstuvwxyz" 
list1=list(chaine1) 
list2=list(chaine2) 
rnd.shuffle(list2) 
code=pd.DataFrame({"Key": list1, "Value" : list2}) 

他設法恢復像這樣的信:

a = code.loc[code['Key'] == 'a', 'Value'] 

於是,他試圖遍歷字來對其進行編碼:

word1="helloworld" 
for char in word1: 
    h=code.loc[code['Key'] == char, 'Value'][0] 

語法是相同的,但它失敗:

KeyError         Traceback (most recent call last) 
<ipython-input-88-4e2a59e0978e> in <module>() 
     1 word1="helloworld" 
     2 for char in word1: 
----> 3  h=code.loc[code['Key'] == char, 'Value'][0] 

~/Envs/test_bapt/lib/python3.5/site-packages/pandas/core/series.py in __getitem__(self, key) 
    599   key = com._apply_if_callable(key, self) 
    600   try: 
--> 601    result = self.index.get_value(self, key) 
    602 
    603    if not is_scalar(result): 

~/Envs/test_bapt/lib/python3.5/site-packages/pandas/core/indexes/base.py in get_value(self, series, key) 
    2475   try: 
    2476    return self._engine.get_value(s, k, 
-> 2477           tz=getattr(series.dtype, 'tz', None)) 
    2478   except KeyError as e1: 
    2479    if len(self) > 0 and self.inferred_type in ['integer', 'boolean']: 

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4404)() 

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value (pandas/_libs/index.c:4087)() 

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5126)() 

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:14031)() 

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:13975)() 

KeyError: 0 

我想通了.values失蹤:h=code.loc[code['Key'] == char, 'Value'][0]。 但有人知道爲什麼第一行工作?我認爲遍歷一個字符串仍然會返回一個字符串。也許我錯過了一些東西,它來自熊貓。我正在運行的版本'0.20.3'

編輯:當我貼我的a定義忘記[0]它應該是:

a = code.loc[code['Key'] == 'a', 'Value'][0] 

對不起徹底難倒我的帖子的點。我想明白爲什麼它在這個簡單的情況下工作,而不是在迭代過程中。

+1

您的問題已得到解答,但請注意,在這種特殊情況下使用'pandas.Dataframe'是無用的。一個'dict'可能是最好的方法(在zip(list1,list2)}中用'code = {k:v代替(k,v)}')。 – FabienP

+0

我完全同意,我會用'dict'代替。但我想明白爲什麼這個簡單的例子失敗了,請看我的帖子底部的**編輯**。對不起,一塌糊塗。 – MCMZL

回答

0

由於@FabianP在評論中指出:這裏不需要

ILOC。與LOC使用的切片已經返回一個字符(作爲系列),所以在這裏[0]試圖索引的字符,這是不可迭代

它不返回一個數組,因而當使用'切片[0]'你不需要第一個元素,但它是一個基於索引的分片 - 因爲對象是pd.Series。它爲char'a'起作用的事實是由於'a'是liste1的第一個字母,因此其索引爲0。

1

只需刪除[0]在H歸屬的末尾:

import random as rnd 
import pandas as pd 

chaine1="abcdefghijklmnopqrstuvwxyz" 
chaine2="abcdefghijklmnopqrstuvwxyz" 
list1=list(chaine1) 
list2=list(chaine2) 
rnd.shuffle(list2) 
code=pd.DataFrame({"Key": list1, "Value" : list2}) 

word1="helloworld" 
for char in word1: 
    print(char) 
    h=code.loc[code['Key'] == char, 'Value'] 
    print(h) 

我加了兩個印記,以確保代碼真的做了什麼,他應該,我得到如下結果:

h 
7 e 
Name: Value, dtype: object 
e 
4 m 
Name: Value, dtype: object 
l 
11 t 
Name: Value, dtype: object 
l 
11 t 
Name: Value, dtype: object 
o 
14 j 
Name: Value, dtype: object 
w 
22 d 
Name: Value, dtype: object 
o 
14 j 
Name: Value, dtype: object 
r 
17 i 
Name: Value, dtype: object 
l 
11 t 
Name: Value, dtype: object 
d 
3 f 
Name: Value, dtype: object 
+0

我同意你的方法,我只是犯了一個錯誤複製粘貼'a'的公式,這改變了我的問題。請在帖子中看到我的**編輯**。 – MCMZL

0

如果您的退貨沒有標記爲「0」,那麼您將返回一個關鍵錯誤。例如你的回報是這樣的:

​​

然後,是的,你會得到一個keyerror。在Pandas中,你想爲整數位置做一個iloc來查找第一條記錄。使用.iloc

word1="helloworld" 
for char in word1: 
    h=code.loc[code['Key'] == char, 'Value'].iloc[0] 

word1 = 'helloworld' 
encoding=[] 
for char in word1: 
    h = code.loc[code['Key'] == char, 'Value'].iloc[0] 
    encoding.append(h) 
enc = ''.join(encoding) 
print(enc) 

輸出:

uayyzvzeyf 
+0

'iloc'在這裏不需要。與'loc'一起使用的片已經返回一個字符(作爲一個系列),所以這裏'[0]'試圖索引字符,這是不可迭代的。 – FabienP

+0

@FabienP你確定嗎?您嘗試從上面的代碼中刪除.iloc? –

+0

是的,它有效(這裏是'pandas 19.2',而不是談論'編碼'部分,這是一個詳細說明,但沒有要求回答這個問題)。以@Erlinska的答案爲例。如果你嘗試'code.loc [code ['Key'] =='b','Value'] * 2',你只會得到''熊貓系列)。 – FabienP