Please answer the following question. Question title: How to get rid of the in place…
Private research annotation
Sign in to add a private research label or note.
- User
Please answer the following question.
Question title: How to get rid of the in place FutureWarning when setting an entire column from an array?
Question body: In pandas v.1.5.0 a new warning has been added, which is shown, when a column is set from an array of different dtype. The FutureWarning informs about a planned semantic change, when using iloc: the change will be done in-place in future versions. The changelog instructs what to do to get the old behavior, but there is no hint how to handle the situation, when in-place operation is in fact the right choice. The example from the changelog: df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2']) original_prices = df['price'] new_prices = np.array([98, 99]) df.iloc[:, 0] = new_prices df.iloc[:, 0] This is the warning, which is printed in pandas 1.5.0: FutureWarning: In a future version, df.iloc[:, i] = newvals will attempt to set the values inplace instead of always setting a new array. To retain the old behavior, use either df[df.columns[i]] = newvals or, if columns are non-unique, df.isetitem(i, newvals) How to get rid of the warning, if I don't care about in-place or not, but want to get rid of the warning? Am I supposed to change dtype explicitly? Do I really need to catch the warning every single time I need to use this feature? Isn't there a better way?
- Assistant
You can get rid of the warning by using the
.locaccessor instead of.iloc. The warning is caused by the in-place assignment with.ilocand to avoid the warning you can use.locaccessor.Example: df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2']) original_prices = df['price'] new_prices = np.array([98, 99]) df.loc[:, 'price'] = new_prices df.loc[:, 'price']
Another way is to use the
.assignmethod, which returns a new DataFrame with the column added or modified.Example: df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2']) original_prices = df['price'] new_prices = np.array([98, 99]) df = df.assign(price=new_prices)
Or, if you need to keep the original DataFrame, you can use the
copymethod to create a copy of the DataFrame first, then assign the column to the copy, which will not trigger the warning.Example: df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2']) original_prices = df['price'] new_prices = np.array([98, 99]) df_copy = df.copy() df_copy.iloc[:, 0] = new_prices df_copy.iloc[:, 0]