4
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 1 year has passed since last update.

pandas.DataFrame同士の計算結果が全てNaNになる時の原因と解決方法

Last updated at Posted at 2023-06-23

1つのDataFrame同士の計算結果が全てNaNになってしまう、といったことがあったのでその原因と解決方法を書きます。

行いたいこと

次のようなabが各教科2回ずつ行ったテスト結果、gradesがあるとします。

>>grades

   Japanese  math  Engilsh name  times
0        25     6       53    a      1
1        84    13       78    b      1
2        18    91       17    a      2
3        32    16       31    b      2

ここからabそれぞれについて、2回のテストの各教科毎の合計点を求めたいとします。
(欲しい出力↓)

   Japanese  math  Engilsh
0        43    97       70
1       116    29      109

最初にやったこと

times列で分割したもので計算したところ、以下のように全てNaNのDataFrameが出力されました。

>>first_grades = grades[grades['times'] == 1].sort_values('name')
>>second_grades = grades[grades['times'] == 2].sort_values('name')
>>first_grades.iloc[:, :-2] + second_grades.iloc[:, :-2]

   Japanese  math  Engilsh
0       NaN   NaN      NaN
1       NaN   NaN      NaN
2       NaN   NaN      NaN
3       NaN   NaN      NaN

原因

原因はインデックスが揃っていないことでした。DataFrame同士の演算結果はインデックスが揃っていない箇所や、列名が違う箇所はNaNで補うようになっています。

>>first_grades

   Japanese  math  Engilsh name  times
0        25     6       53    a      1
1        84    13       78    b      1

>>second_grades

   Japanese  math  Engilsh name  times
2        18    91       17    a      2
3        32    16       31    b      2

解決方法

reset_index()を使ってインデックスが揃うように振り直して計算すると、欲しい結果が得られます。

# インデックスの振り直しと元のインデックス列の削除
>>first_grades = first_grades.reset_index().drop('index', axis=1)
>>first_grades

   Japanese  math  Engilsh name  times
0        25     6       53    a      1
1        84    13       78    b      1

>>second_grades = second_grades.reset_index().drop('index', axis=1)
>>second_grades

   Japanese  math  Engilsh name  times
0        18    91       17    a      2
1        32    16       31    b      2

>>first_grades.iloc[:, :-2] + second_grades.iloc[:, :-2]

   Japanese  math  Engilsh
0        43    97       70
1       116    29      109
4
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
4
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?