6
4

More than 3 years have passed since last update.

pandasのエラー対処法(備忘録)

Posted at

1. はじめに

本記事は備忘録であり、人に見せようと思って書いているものではありません。そのため、分かりにくい表現やニッチな内容が含まれているかもしれません。

2. mergeができない

merge.py
import pandas as pd
import numpy as np

a = np.range(9).reshape(3,3)
b = np.range(9).reshape(3,3)

df_a = pd.DataFrame(a, columns=['A', 'B', 'C'])
df_b = pd.DataFrame(b, columns=[['A', 'B', 'D']])

print(df_a)
print(df_b)

とすると

merge_output.py
   A  B  C
0  0  1  2
1  3  4  5
2  6  7  8
   A  B  D
0  0  1  2
1  3  4  5
2  6  7  8

のように出力される。
このdf_aとdf_bをmergeしたい。

merge.py
df_c = pd.merge(df_a, df_b, how='left')

すると、下のようなエラーメッセージが出てくる。

pandas.errors.MergeError: No common columns to perform merge on. Merge options: left_on=None, right_on=None, left_index=False, right_index=False

これは、共通するカラムがないのでmergeができませんと言っている。
df_aとdf_bでカラム'A','B'が共通しているはず。

カラムのデータタイプをそれぞれ調べる。

check_df_column.py
print(type(df_a.column))
print(type(df_b.column))

すると

output
<class 'pandas.core.indexes.base.Index'>
<class 'pandas.core.indexes.multi.MultiIndex'>

となっており、columnの型が異なっていたことが分かる。
これは、DataFrameを作る時に、
df_bのカラムはcolumn=[['A', 'B', 'D']]としていたため。
これをdf_aと同じようにする。

merge.py
import pandas as pd
import numpy as np

a = np.range(9).reshape(3,3)
b = np.range(9).reshape(3,3)

df_a = pd.DataFrame(a, columns=['A', 'B', 'C'])
df_b = pd.DataFrame(b, columns=['A', 'B', 'D'])

df_c = pd.merge(df_a, df_b, how='left')
print(df_c)
output
   A  B  C  D
0  0  1  2  2
1  3  4  5  5
2  6  7  8  8

となり、修正することができた。

6
4
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
6
4