### 内容
下記のtsvファイル(test.log)を読み、pandasのdataframeに入れて、
I列が3の行を抽出したいと思っています。
該当のソースコード
df = pd.read_csv(work_dir + "/test.log", delimiter='\t', engine='python') df.loc[df['I'] == 3,:]
しかし、
if is_scalar(key) and isna(key) and not self.hasnans:
KeyError: 'I'
のエラーが出て、抽出できません。
dtypesは以下のようになっています。
I int64 J int64 A float64 B float64 C float64 D float64 E float64 F float64 G float64 dtype: object
KeyErrorが出る原因が全く分からないのですが、どなたか原因がわかる方教えていただけないでしょうか。
発生している問題・エラーメッセージ
KeyError Traceback (most recent call last) ~/miniforge3/envs/py38/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3360 try: -> 3361 return self._engine.get_loc(casted_key) 3362 except KeyError as err: ~/miniforge3/envs/py38/lib/python3.8/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() ~/miniforge3/envs/py38/lib/python3.8/site-packages/pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'I' The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) /tmp/ipykernel_5373/2437506938.py in <module> ----> 1 df.loc[df_map['I'] == 3,:] ~/miniforge3/envs/py38/lib/python3.8/site-packages/pandas/core/frame.py in __getitem__(self, key) 3453 if self.columns.nlevels > 1: 3454 return self._getitem_multilevel(key) -> 3455 indexer = self.columns.get_loc(key) 3456 if is_integer(indexer): 3457 indexer = [indexer] ~/miniforge3/envs/py38/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3361 return self._engine.get_loc(casted_key) 3362 except KeyError as err: -> 3363 raise KeyError(key) from err 3364 3365 if is_scalar(key) and isna(key) and not self.hasnans: KeyError: 'I'
補足情報(FW/ツールのバージョンなど)
python3.8
jupyter notebook
すみません、一部、間違えていました。
【誤】df.loc[df_map['I'] == 3,:]
↓
【正】df.loc[df['I'] == 3,:]
ただ、df.loc[df['I'] == 3,:]でも、エラー内容は同じで、KeyErrorが出ます。
元の TSV ファイルですが、ヘッダ行の I の前後にスペース(0x20)が入っていたりはしませんか?
> すみません、一部、間違えていました。
質問は編集できますので質問を編集しましょう。
print(df.columns) でカラム名を確認されると良いかもしれません。
TSVファイルを確認したところ、tabの前に余計なスペースが入っていたようです。
全の列のtabを確認して修正したら、ちゃんと読み込めるようになりました。
皆様、有難うございました。

回答1件
あなたの回答
tips
プレビュー