86
60

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

辞書をpd.DataFrameに変換

Last updated at Posted at 2019-05-22

異なる長さのリストを含む辞書をpd.DataFrameに変換

dict_to_df.py
#!/usr/bin/env python3
import pandas as pd

d1={'key1': [1,2,3], 'key2': [4,5,6,7], 'key3': [8,9]}

d2={}
for k,v in d1.items():   # 一度pd.Seriesに変換
    d2[k]=pd.Series(v)

df=pd.DataFrame(d2)

print(df)
   key1  key2  key3
0   1.0     4   8.0
1   2.0     5   9.0
2   3.0     6   NaN
3   NaN     7   NaN

追記 (より良い方法)

以下のコメントでnkayさんから良い方法を教えていただきました。
とても簡潔にpd.DataFrameに変換できます。

d = {'key1': [1,2,3], 'key2': [4,5,6,7], 'key3': [8,9]}

df = pd.DataFrame.from_dict(d, orient='index').T
# もしくは
df = pd.DataFrame(d.values(), index=d.keys()).T

print(df)
   key1  key2  key3
0   1.0   4.0   8.0
1   2.0   5.0   9.0
2   3.0   6.0   NaN
3   NaN   7.0   NaN

これはできない

ValueError: arrays must all be same lengthのエラーが出る

d={'key1': [1,2,3], 'key2': [4,5,6,7], 'key3': [8,9]}
df=pd.DataFrame(d)  # これはできない

辞書に含まれるリストの長さが同じ時のみ、可能

d={'key1': [1,2,3], 'key2': [4,5,6], 'key3': [7,8,9]}
df=pd.DataFrame(d)  # これはできる

print(df)
   key1  key2  key3
0     1     4     7
1     2     5     8
2     3     6     9

環境

Ubuntu 18.04
Python 3.7.2
pandas 0.24.1

86
60
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
86
60

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?