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

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

新規登録して質問してみよう
ただいま回答率
85.47%
NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

Q&A

解決済

1回答

648閲覧

データフレームの要素を数値で行列表記したい

shu214

総合スコア18

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

0グッド

0クリップ

投稿2019/11/15 13:30

編集2019/11/17 11:08

前提・実現したいこと

テキストデータとして出力された動画内の動く人物の座標データを処理したいです。
それぞれの要素がobject型になっているのをfloat型に直して、さらに(x,y)のように行列表記をしたいです。
以下のようなデータが85行分あります。

0:517.5 669.5:person, 106.0 462.0:person, 396.0 362.5:person, 646.5 377.0:person,
1:516.5 666.0:person, 106.0 458.5:person, 386.5 362.5:person, 654.5 378.0:person, 36.5 459.5:person,
2:506.5 660.0:person, 107.0 454.0:person, 654.5 393.0:person, 386.5 369.0:person,
3:508.0 661.5:person, 106.0 452.5:person, 380.5 361.0:person, 653.0 394.0:person,
4:510.0 663.0:person, 106.5 454.0:person, 649.5 388.5:person, 380.5 364.0:person,
5:107.0 456.0:person, 650.5 390.5:person, 510.5 661.5:person, 383.0 365.5:person,

発生している問題・エラーメッセージ

ValueError Traceback (most recent call last) <ipython-input-5-5e185effa98f> in <module>() 18 data.E = data.E.str.split() 19 ---> 20 data = data.astype(np.float) 21 22 data 5 frames /usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in astype(self, dtype, copy, errors, **kwargs) 5880 # else, only a single dtype is given 5881 new_data = self._data.astype( -> 5882 dtype=dtype, copy=copy, errors=errors, **kwargs 5883 ) 5884 return self._constructor(new_data).__finalize__(self) /usr/local/lib/python3.6/dist-packages/pandas/core/internals/managers.py in astype(self, dtype, **kwargs) 579 580 def astype(self, dtype, **kwargs): --> 581 return self.apply("astype", dtype=dtype, **kwargs) 582 583 def convert(self, **kwargs): /usr/local/lib/python3.6/dist-packages/pandas/core/internals/managers.py in apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs) 436 kwargs[k] = obj.reindex(b_items, axis=axis, copy=align_copy) 437 --> 438 applied = getattr(b, f)(**kwargs) 439 result_blocks = _extend_blocks(applied, result_blocks) 440 /usr/local/lib/python3.6/dist-packages/pandas/core/internals/blocks.py in astype(self, dtype, copy, errors, values, **kwargs) 557 558 def astype(self, dtype, copy=False, errors="raise", values=None, **kwargs): --> 559 return self._astype(dtype, copy=copy, errors=errors, values=values, **kwargs) 560 561 def _astype(self, dtype, copy=False, errors="raise", values=None, **kwargs): /usr/local/lib/python3.6/dist-packages/pandas/core/internals/blocks.py in _astype(self, dtype, copy, errors, values, **kwargs) 641 # _astype_nansafe works fine with 1-d only 642 vals1d = values.ravel() --> 643 values = astype_nansafe(vals1d, dtype, copy=True, **kwargs) 644 645 # TODO(extension) /usr/local/lib/python3.6/dist-packages/pandas/core/dtypes/cast.py in astype_nansafe(arr, dtype, copy, skipna) 727 if copy or is_object_dtype(arr) or is_object_dtype(dtype): 728 # Explicit copy, or required since NumPy can't view from / to object. --> 729 return arr.astype(dtype, copy=True) 730 731 return arr.view(dtype) ValueError: setting an array element with a sequence.

該当のソースコード

import pandas as pd import numpy as np data = pd.read_table('basket.data.txt',names=('A','B','C','D','E'),sep=',') data.A = data.A.str.replace('^[0-9]+:','') data.A = data.A.str.strip(':person') data.B = data.B.str.strip(':person') data.C = data.C.str.strip(':person') data.D = data.D.str.strip(':person') data.E = data.E.str.strip(':person') data.A = data.A.str.split() data.B = data.B.str.split() data.C = data.C.str.split() data.D = data.D.str.split() data.E = data.E.str.split() data = data.astype(np.float) data

ネットに記載されているものは一通りやってみたのですが、どれも自分ではうまくいきませんでした。
それができれば、最近傍法をつかって同一人物を判定してそれぞれの列に並び変えることに挑戦します。それに関してもヒントなどあれば教えていただきたいです。
よろしくお願いします。

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

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

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

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

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

meg_

2019/11/17 01:49

エラーメッセージは全文掲載しましょう。
shu214

2019/11/17 11:09

初めてなもので、質問の仕方が悪かったです。申し訳ございません。 更新しました。
guest

回答1

0

ベストアンサー

こう・・かな?
(x,y)表記はとりあえずタプルにしてみました。

Python

1import pandas as pd 2import numpy as np 3 4data = pd.read_table('basket.data.txt',names=('A','B','C','D','E'),sep=',') 5 6data.A = data.A.str.replace('^[0-9]+:','') 7 8data.A = data.A.str.strip(':person') 9data.B = data.B.str.strip(':person') 10data.C = data.C.str.strip(':person') 11data.D = data.D.str.strip(':person') 12data.E = data.E.str.strip(':person') 13 14data.A = data.A.str.split() 15data.B = data.B.str.split() 16data.C = data.C.str.split() 17data.D = data.D.str.split() 18data.E = data.E.str.split() 19 20 21print(type(data.loc[0, 'A'][0])) 22""" 23<class 'str'> 24""" 25 26data = data.applymap(lambda x: tuple(np.array(x).astype(np.float)) if np.array(x).ndim != 0 else x) 27print(data) 28""" 29 A B C D E 300 (517.5, 669.5) (106.0, 462.0) (396.0, 362.5) (646.5, 377.0) NaN 311 (516.5, 666.0) (106.0, 458.5) (386.5, 362.5) (654.5, 378.0) (36.5, 459.5) 322 (506.5, 660.0) (107.0, 454.0) (654.5, 393.0) (386.5, 369.0) NaN 333 (508.0, 661.5) (106.0, 452.5) (380.5, 361.0) (653.0, 394.0) NaN 344 (510.0, 663.0) (106.5, 454.0) (649.5, 388.5) (380.5, 364.0) NaN 355 (107.0, 456.0) (650.5, 390.5) (510.5, 661.5) (383.0, 365.5) NaN 36""" 37 38 39print(type(data.loc[0, 'A'][0])) 40""" 41<class 'numpy.float64'> 42"""

私の当初環境ではE列にスペースが入っていたため、NaNが混入していなかったみたいです。

スペースを消してNaNを混入した状態に対応してみました。

データが入っていればdata.?.str.split()によって1次元配列ができています。
NaNの場合は1次元配列にならずそのままデータが残ります。
それをnp.array(x).ndim != 0で見分けます。NaNを別の値にしたい場合は最後のxを別の式に置き換えてください。

投稿2019/11/17 08:03

編集2019/11/17 12:15
nomuken

総合スコア1627

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

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

shu214

2019/11/17 11:35

TypeError Traceback (most recent call last) <ipython-input-18-5ef9437ac67e> in <module>() ----> 1 data = data.applymap(lambda x: tuple(np.array(x).astype(np.float))) 2 print(data) 6 frames /usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in applymap(self, func) 6992 return lib.map_infer(x.astype(object).values, func) 6993 -> 6994 return self.apply(infer) 6995 6996 # ---------------------------------------------------------------------- /usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds) 6926 kwds=kwds, 6927 ) -> 6928 return op.get_result() 6929 6930 def applymap(self, func): /usr/local/lib/python3.6/dist-packages/pandas/core/apply.py in get_result(self) 184 return self.apply_raw() 185 --> 186 return self.apply_standard() 187 188 def apply_empty_result(self): /usr/local/lib/python3.6/dist-packages/pandas/core/apply.py in apply_standard(self) 290 291 # compute the result using the series generator --> 292 self.apply_series_generator() 293 294 # wrap results /usr/local/lib/python3.6/dist-packages/pandas/core/apply.py in apply_series_generator(self) 319 try: 320 for i, v in enumerate(series_gen): --> 321 results[i] = self.f(v) 322 keys.append(v.name) 323 except Exception as e: /usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in infer(x) 6990 if x.empty: 6991 return lib.map_infer(x, func) -> 6992 return lib.map_infer(x.astype(object).values, func) 6993 6994 return self.apply(infer) pandas/_libs/lib.pyx in pandas._libs.lib.map_infer() <ipython-input-18-5ef9437ac67e> in <lambda>(x) ----> 1 data = data.applymap(lambda x: tuple(np.array(x).astype(np.float))) 2 print(data) TypeError: ('iteration over a 0-d array', 'occurred at index E') こういうエラーが出ました。 5行分のデータには入ってないのですが、要素のない箇所がけっこうありまして、そこでどうやらエラーがおこっているようです。if文とかで対処できるのでしょうか?
shu214

2019/11/17 12:50

すごい! できました!!! ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.47%

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

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

質問する

関連した質問