1

dictionary型のlistがあります。中身は以下のようにnode、feature、labelというキーがあります。

sample_list = [
{'node': 12345, 'feature': [0.0, 1.0, 0.0, 0.0], 'label': 'b'},
{'node': 9921821, 'feature': [0.0, 0.0, 1.0, 0.0], 'label': 'c'},
{'node': 122, 'feature': [1.0, 0.0, 0.0, 0.0], 'label': 'a'},
]

このlistからfeatureキーの値を取り出してnumpyのndarrayとしたいです。
上のsample_listを例にとると、欲しいものは以下のようになります。

[[0.0 1.0 0.0 0.0], [0.0 0.0 1.0 0.0], [1.0 0.0 0.0 0.0]]  # type numpy.ndarray, shape = (3, 4)

どなたかわかる方いらっしゃいましたら教えてください。よろしくお願いします

追記
nodeキーの値とlabelキーの値をpandas.Series型に保存する方法も教えてください。
上記の例ですと欲しいものは以下のデータになります。

12345  b
9921821  c
122  a

2 件の回答 2

1

内包表記の例です。

sample_list = [
{'node': 12345, 'feature': [0.0, 1.0, 0.0, 0.0], 'label': 'b'},
{'node': 9921821, 'feature': [0.0, 0.0, 1.0, 0.0], 'label': 'c'},
{'node': 122, 'feature': [1.0, 0.0, 0.0, 0.0], 'label': 'a'},
]

import numpy as np

ar = np.array([d['feature'] for d in sample_list])
print(ar)

import pandas as pd

sl = pd.Series([d['label'] for d in sample_list], index=[d['node'] for d in sample_list])
print(sl)
1

以下は sample listpandas.DataFrame に変換して処理する方法です。

import pandas as pd
import numpy as np

df = pd.DataFrame(sample_list)

features = np.vstack(df.feature)
print(f'features:\n{features}')
print(f'\ntype: {type(features)}, shape={features.shape}')

nodes_label = df.set_index('node').label
print(f'\nnodes label:\n{nodes_label}')
print(f'\ntype: {type(nodes_label)}')

##
features:
[[0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [1. 0. 0. 0.]]

type: <class 'numpy.ndarray'>, shape=(3, 4)

nodes label:
node
12345      b
9921821    c
122        a
Name: label, dtype: object

type:<class 'pandas.core.series.Series'>

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。