In the example code below, I am adding a NumPy array to a Pandas DataFrame. To avoid a SettingWithCopyWarning, I rewrote the code, but now I am getting a KeyError instead:
"None of [MultiIndex([('new', 0),\n ('new', 1),\n ('new', 2)],\n )] are in the [columns]"
This is not wrong, as the given columns are not in the columns. But why do they need to be?
import numpy as np
import pandas as pd
df_ = pd.DataFrame(range(10), columns=[["old"], [0]])
df = df_[df_.old[0] < 4]
arr = np.random.randn(4, 3)
indices = pd.MultiIndex.from_product([["new"], range(arr.shape[-1])])
# A value is trying to be set on a copy of a slice from a DataFrame.
# Try using .loc[row_indexer,col_indexer] = value instead
# df[indices] = pd.DataFrame(arr, index=df.index)
# OK - I did that! This works after the previous line, but not without it:
df.loc[:, indices] = pd.DataFrame(arr, index=df.index)