pandas : SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.

どちらでも Warning:

1
2
3
4
5
6
    def _balance(df):
        if df["bookitem_kind"] == "1":
            return -1 * df["amount"]
        return df["amount"]

    df_epm_cost["amount2"] = df_epm_cost.apply(_balance, axis=1)
1
df_epm_cost["amount"].where(df_epm_cost["bookitem_kind"] == "0", -1 * df_epm_cost["amount"], inplace=True)

ValueError: cannot reindex on an axis with duplicate labels

1
df_epm_cost.loc[df_epm_cost["bookitem_kind"] == "1", "amount2"] = df_epm_cost["amount"] * (-1)
  • FutureWarning: reindexing with a non-unique Index is deprecated and will raise in a future version
  • ValueError: cannot reindex on an axis with duplicate labels

インデックスを削除するとうまく行く:

1
df_epm_cost = df_epm_cost.reset_index(drop=True)

インデックスを削除すると where でもうまく行く:

1
df_epm_cost["amount"].where(df_epm_cost["bookitem_kind"] == "0", -1 * df_epm_cost["amount"], inplace=True)

記事