ChainedAssignmentError beim Hinzufügen einer Bedingung zu einem Pandas-DatenrahmenPython

Python-Programme
Anonymous
 ChainedAssignmentError beim Hinzufügen einer Bedingung zu einem Pandas-Datenrahmen

Post by Anonymous »

Ich erhalte ständig einen ChainedAssignmentError, wenn ich eine Bedingung zu meinem Code hinzufüge. In diesem einfachen Beispiel überprüfe ich, ob Spalte „eins“ ein „e“ ist, und wenn ja, setze ich die Spalte „Übereinstimmung“ auf 1.
Die df wird korrekt aktualisiert, ich erhalte nur die FutureWarning.

Code: Select all

import pandas as pd

df = pd.DataFrame([list('ab0'),
list('ee0'),
list('ij0'),
list('ii0')],
columns=['one', 'two', 'Match'])
print(df)

df.loc[:,"Match"][df.loc[:,"one"] == "e"] = 1

print(df)
AUSGABE

Code: Select all

one two Match

0   a   b     0

1   e   e     0

2   i   j     0

3   i   i     0

FutureWarning: ChainedAssignmentError: behaviour will change in pandas 3.0!
You are setting values through chained assignment. Currently this works in certain cases, but when using Copy-on-Write (which will become the default behaviour in pandas 3.0) this will never work to update the original DataFrame or Series, because the intermediate object on which we are setting values will behave as a copy.
A typical example is when you are setting values in a column of a DataFrame, like:

df["col"][row_indexer] = value

Use `df.loc[row_indexer, "col"] = values` instead, to perform the assignment in a single step and ensure this keeps updating the original `df`.

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

one two Match

0   a   b     0

1   e   e     1

2   i   j     0

3  i   i     0

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post