correct accessing of slices with duplicate index-values present

Viewed 1523

I have a dataframe with an index that sometimes contains rows with the same index-value. Now I want to slice that dataframe and set values based on row-indices.

Consider the following example:

import pandas as pd

df = pd.DataFrame({'index':[1,2,2,3], 'values':[10,20,30,40]})
df.set_index(['index'], inplace=True)

df1 = df.copy()
df2 = df.copy()

#copy warning
df1.iloc[0:2]['values'] = 99
print(df1)

df2.loc[df.index[0:2], 'values'] = 99
print(df2)

df1 is the expected result, but gives me a SettingWithCopyWarning. df2 seems to be the suggested way of accessing by the doc, but gives me the wrong result (because of the duplicate index)

Is there a "proper" way to set those values correctly with the duplicate index-values present?

1 Answers
Related