質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

6373閲覧

Pythonでデータフレームの列抽出が出来ないです

_hh

総合スコア79

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2018/11/01 07:19

jupyter notebookを用いて、テキスト形式のデータを読み込もうとしておりますが、いまくいきません。"housing.data"の、一番右側の13列目をyという値で読み込もうとして、以下のコードを試しております。原因と対処につき、ご教示願います。
【コード】
import pandas as pd
import numpy as np
d = pd.read_csv('housing.data.txt',header=None)

d.head()
y=d.iloc(d[:,12:13])
print(y)

【エラー】
TypeError: unhashable type: 'slice'

【環境】Windows64bit, chrome

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

結果をSeriesとして読み込みたい場合は

Python

1y=d.iloc[:,12]

結果をDataFrameとして読み込みたい場合は

Python

1y=d.iloc[:,[12]]

で良いかと思います。

投稿2018/11/01 07:33

magichan

総合スコア15898

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

_hh

2018/11/01 07:42

有難うございます。しかし、以下の様なエラーが出てしまいます: IndexError Traceback (most recent call last) <ipython-input-31-64c2563fbaf4> in <module>() 4 5 d.head() ----> 6 y=d.iloc[:,[12]] 7 #y=d.iloc(d[:,[12]]) 8 print(y) ~\Miniconda3\envs\stats\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key) 1470 except (KeyError, IndexError): 1471 pass -> 1472 return self._getitem_tuple(key) 1473 else: 1474 # we by definition only have the 0th axis ~\Miniconda3\envs\stats\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup) 2011 def _getitem_tuple(self, tup): 2012 -> 2013 self._has_valid_tuple(tup) 2014 try: 2015 return self._getitem_lowerdim(tup) ~\Miniconda3\envs\stats\lib\site-packages\pandas\core\indexing.py in _has_valid_tuple(self, key) 220 raise IndexingError('Too many indexers') 221 try: --> 222 self._validate_key(k, i) 223 except ValueError: 224 raise ValueError("Location based indexing can only have " ~\Miniconda3\envs\stats\lib\site-packages\pandas\core\indexing.py in _validate_key(self, key, axis) 1966 1967 if len(arr) and (arr.max() >= l or arr.min() < -l): -> 1968 raise IndexError("positional indexers are out-of-bounds") 1969 else: 1970 raise ValueError("Can only index by location with " IndexError: positional indexers are out-of-bounds
magichan

2018/11/01 07:47

print(d.shape) にて行数と列数を表示してみてください 列数は13列以上ありますか?
_hh

2018/11/01 07:51

(506,1)とでました。しかし、、print(d)で表示しますと、以下の様に14列のデータで、元データもそのような形なのですが、、、さっぱりです。。 0 0.00632 18.00 2.310 0 0.5380 6.5750 65... 1 0.02731 0.00 7.070 0 0.4690 6.4210 78... 2 0.02729 0.00 7.070 0 0.4690 7.1850 61... 3 0.03237 0.00 2.180 0 0.4580 6.9980 45... 4 0.06905 0.00 2.180 0 0.4580 7.1470 54...
magichan

2018/11/01 07:53

おそらくデータ読み込み時に、列データが分割されずに1つの長い文字列として読み込まれているのかと思います。
_hh

2018/11/01 08:01

有難うございます。以下の様に、スペース区切りをして読み込もうとしたのですが、下記の様なエラーが出てしまいました。 【コード】 import pandas as pd import numpy as np d = pd.read_csv('housing.data.txt',header=None,sep=" ") d.head() print(d.shape) print(d) 【エラー】 ParserError Traceback (most recent call last) <ipython-input-43-9bbe756de067> in <module>() 1 import pandas as pd 2 import numpy as np ----> 3 d = pd.read_csv('housing.data.txt',header=None,sep=" ") 4 d.head() 5 print(d.shape) ~\Miniconda3\envs\stats\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, doublequote, delim_whitespace, low_memory, memory_map, float_precision) 676 skip_blank_lines=skip_blank_lines) 677 --> 678 return _read(filepath_or_buffer, kwds) 679 680 parser_f.__name__ = name ~\Miniconda3\envs\stats\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 444 445 try: --> 446 data = parser.read(nrows) 447 finally: 448 parser.close() ~\Miniconda3\envs\stats\lib\site-packages\pandas\io\parsers.py in read(self, nrows) 1034 raise ValueError('skipfooter not supported for iteration') 1035 -> 1036 ret = self._engine.read(nrows) 1037 1038 # May alter columns / col_dict ~\Miniconda3\envs\stats\lib\site-packages\pandas\io\parsers.py in read(self, nrows) 1846 def read(self, nrows=None): 1847 try: -> 1848 data = self._reader.read(nrows) 1849 except StopIteration: 1850 if self._first_chunk: pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows() pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._tokenize_rows() pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error() ParserError: Error tokenizing data. C error: Expected 30 fields in line 2, saw 31
magichan

2018/11/01 08:12

エラーの意訳 『データの数が30個であることを期待して解析しましたが、line2 には 31個のデータがありました』 だそうです
_hh

2018/11/01 08:33

有難うございます。"delim_whitespace=True" としたところ、うまくいきました。有難うございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問