質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

1041閲覧

データフレームを参照し条件を満たせば特定のデータを入れたい

tomoysh

総合スコア42

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2022/03/06 08:55

編集2022/03/06 11:26

前提・実現したいこと

ここに質問の内容を詳しく書いてください。
(例)PHP(CakePHP)で●●なシステムを作っています。
■■な機能を実装中に以下のエラーメッセージが発生しました。

発生している問題・エラーメッセージ

ValueError: cannot reindex from a duplicate axis

該当のソースコード

python

1all_df.loc[all_df['データa'] == all_df['データb'], 'データc'] = all_df['データc'] 2

データフレームからデータaとデータbを参照し、同じならデータcにデータbのデータを入れて、新しいカラムを作りたいと考えています。
上記のエラーにより該当のコードでは実行できませんでした。解決方法を教えていただけないでしょうか?

追記

掲載したコードが誤りでした。正しくは以下のコードでした。

python

1all_df.loc[all_df['データa'] == all_df['データb'], 'データc'] = all_df['データb'] 2

以下エラーの全文になります。
ValueError Traceback (most recent call last)
/var/folders/71/9_gw2z712yx4ccsvb21s9kh80000gn/T/ipykernel_28537/4172916488.py in <module>
----> 1 all_df.loc[all_df['データa'] == all_df['データb'], 'データc'] = all_df['データb']

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/indexing.py in setitem(self, key, value)
721
722 iloc = self if self.name == "iloc" else self.obj.iloc
--> 723 iloc._setitem_with_indexer(indexer, value, self.name)
724
725 def _validate_key(self, key, axis: int):

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/indexing.py in _setitem_with_indexer(self, indexer, value, name)
1728 if take_split_path:
1729 # We have to operate column-wise
-> 1730 self._setitem_with_indexer_split_path(indexer, value, name)
1731 else:
1732 self._setitem_single_block(indexer, value, name)

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/indexing.py in _setitem_with_indexer_split_path(self, indexer, value, name)
1749 from pandas import Series
1750
-> 1751 value = self._align_series(indexer, Series(value))
1752
1753 # Ensure we have something we can iterate over

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/indexing.py in _align_series(self, indexer, ser, multiindex_indexer)
2118 return ser._values.copy()
2119
-> 2120 return ser.reindex(new_ix)._values
2121
2122 # 2 dims

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/series.py in reindex(self, index, **kwargs)
4578 )
4579 def reindex(self, index=None, **kwargs):
-> 4580 return super().reindex(index=index, **kwargs)
4581
4582 @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"])

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/generic.py in reindex(self, *args, **kwargs)
4817 # perform the reindex on the axes
4818 return self._reindex_axes(
-> 4819 axes, level, limit, tolerance, method, fill_value, copy
4820 ).finalize(self, method="reindex")
4821

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/generic.py in _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy)
4841 fill_value=fill_value,
4842 copy=copy,
-> 4843 allow_dups=False,
4844 )
4845

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/generic.py in _reindex_with_indexers(self, reindexers, fill_value, copy, allow_dups)
4887 fill_value=fill_value,
4888 allow_dups=allow_dups,
-> 4889 copy=copy,
4890 )
4891 # If we've made a copy once, no need to make another one

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/internals/managers.py in reindex_indexer(self, new_axis, indexer, axis, fill_value, allow_dups, copy, consolidate, only_slice)
668 # some axes don't allow reindexing with dups
669 if not allow_dups:
--> 670 self.axes[axis]._validate_can_reindex(indexer)
671
672 if axis >= self.ndim:

/opt/anaconda3/envs/machine/lib/python3.7/site-packages/pandas/core/indexes/base.py in _validate_can_reindex(self, indexer)
3783 # trying to reindex on an axis with duplicates
3784 if not self._index_as_unique and len(indexer):
-> 3785 raise ValueError("cannot reindex from a duplicate axis")
3786
3787 def reindex(

ValueError: cannot reindex from a duplicate axis

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

melian

2022/03/06 09:39

エラーメッセージから察するに、all_df の index に重複があるのかもしれません。以下を実行して確認してみて下さい。 print(all_df[all_df.index.duplicated(keep=False)])
meg_

2022/03/06 11:03

> データフレームからデータaとデータbを参照し、同じならデータcにデータbのデータを入れて、新しいカラムを作りたいと考えています。 コードではデータcカラムにデータcカラムのデータを入れようとしているようですが? またエラーメッセージは抜粋ではなく全て掲載された方が良いかと思います。
guest

回答1

0

ベストアンサー

  • 左辺と右辺のインデックスがあっていない
  • 右辺のインデックスの値が重複している

の両者が起こっているためのエラーです。

左辺と右辺のインデックスが一致していればそのまま代入されますが、一致していない場合は右辺を左辺のインデックスに reindex します。
そのとき、値が重複しているとどちらを使うか判断できないので、質問にあるエラーが発生します。

対策としては、インデックスの重複をなくすのが一番いいと思いますが、それが難しければ右辺もlocで絞ってやればいいです。

python

1target = (all_df['データa'] == all_df['データb']) 2all_df.loc[target , 'データc'] = all_df.loc[target , 'データb']

ただ、やりたいことはSeries.whereを使えばできるかもしれません。

python

1all_df['データc'] = all_df['データb'].where(all_df['データa'] == all_df['データb'])

投稿2022/03/07 04:05

bsdfan

総合スコア4560

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問