1
1

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.

メモ: pandas で列を加えるいろんな方法

Last updated at Posted at 2018-01-31

概要

pandas で DataFrame (indexあり) の列を別の DataFrame (同じ構造のindexあり) に加える方法を試す。

※結論: index があえばレコードが一致してなくてもいい。left join 的に足せる。

単純に列を足す

※index があればレコード数が異なっていても問題ない。

import pandas as pd
A = pd.DataFrame(data={'a':[1, 2, 3], 'b': ['b1','b2','b3'], 'c': ['c1','c2','c3']}).set_index('a')
B = pd.DataFrame(data={'a':[   2, 3], 'd': [     'd2','d3'], 'e': [     'e2','e3']}).set_index('a')

# d を足す (Series として足す)
A['d'] = B['d']

# もしくは
# DataFrame として足してもいい
A['d'] = B[['d']]

#    b   c   d
# a
# 1  b1  c1  NaN
# 2  b2  c2  d2
# 3  b3  c3  d3

# NaN の代わりに 0 を入れたいなら、上記のあとで
A['d'] = A['d'].fillna(0)

#    b   c   d
# a
# 1  b1  c1  0
# 2  b2  c2  d2
# 3  b3  c3  d3


# 条件の結果を代入することも可能
A['f'] = (B.d == "d2")

#    b   c   f
# a
# 1  b1  c1  NaN
# 2  b2  c2  True
# 3  b3  c3  False

複数列を同時に加えるなら

import pandas as pd
A = pd.DataFrame(data={'a':[1, 2, 3], 'b': ['b1','b2','b3'], 'c': ['c1','c2','c3']}).set_index('a')
B = pd.DataFrame(data={'a':[   2, 3], 'd': [     'd2','d3'], 'e': [     'e2','e3']}).set_index('a')

A = A.merge(B, how='left', left_index=True, right_index=True)
# もしくは
A['d'] = B.d
A['e'] = B.e

indexが重複していてもleft joinされる

import pandas as pd
A = pd.DataFrame(data={'a':[1, 2, 3], 'b': ['b1','b2','b3'], 'c': ['c1','c2','c3']}).set_index('a')
C = pd.DataFrame(data={'a':[2, 2, 3]}).set_index('a')

C['b'] = A.b

#    b
# a
# 2  b2
# 2  b2
# 3  b3

# 当然だが right 側がキー重複してるとエラー
D = pd.DataFrame(data={'a':[2, 2, 3], 'g':['g1','g2','g3']}).set_index('a')
A['g'] = D.g

# ValueError: cannot reindex from a duplicate axis
1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?