简体   繁体   中英

Assign a value to a cell from another cell

I would like to assign one value from a specific cell from another value of a specific cell from the same dataframe.

I have tried the following:

df.loc[i_list[0]][first_empty_column_unique] = df.iloc[i][index_of_duplicate_element]

but I am getting the following error:

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

I have tried also to copy the df as follows:

elements = df.iloc[i][[index_of_duplicate_element]].copy()
df.loc[i_list[0]][first_empty_column_unique] = elements

but I am still getting the error.

Which is the correct way of copying from one cell to another in my case?

Generally with loc you should write .loc[x, y] instead of .loc[x][y] (same for iloc ):

df.loc[i_list[0], first_empty_column_unique] = df.iloc[i, index_of_duplicate_element]

I had to deal with a similar problem.
richardec's answer shows how to fix it

But if you are also curious on why it wasn't working as you expected, the warning also redirects to a docs page that explains the problem:
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-view-versus-copy

Long story short, when you use double braces, the indexing is done in two steps (row-wise and column-wise), and you might end up operating on a copy of the original.
Conversely, when you use the loc function in one go, a multi-index (row and column) is performed so it is ensured that the changes will affect the original dataframe:

df.loc['row_index']['Column'] = 'SomeValue' #will raise the warning and might not work
df.loc['row_index', 'Column'] = 'SomeValue' #won't raise the warning and works perfectly
````

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM