I wanted to change the value of my row where if the column "state" had the value of "CANCELLED" then it would change the row value from column "Activity" into "Cancelled"
It should be like this:
ID | Activity | state |
---|---|---|
1 | created | CANCELLED |
1 | completed | CANCELLED |
2 | created | FINNISHED |
2 | completed | FINISHED |
3 | created | REJECTED |
3 | rejected | REJECTED |
what i tired using df.loc[df.state == "CANCELLED", "Activity"] = "cancelled"
It did changed the Activity but i still wanted the created activity to be the same.
There's also an error
C:\Users\aldev\miniconda3\lib\site-packages\pandas\core\indexing.py:1720: SettingWithCopyWarning:
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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self._setitem_single_column(loc, value, pi)
If anyone has an answer thank you in advance
df.loc[(df.state == "CANCELLED") & (df.Activity != "created"), "Activity"] = "cancelled"
The code was missed ()
, in the (df.state == "CANCELLED")
We need to find the rows where the state = 'cancelled'. We can use the .loc(row, column)
operator to select the entries where state = 'cancelled' and return the 'Activity' column we then just replace those values with 'cancelled'
import pandas as pd
data = {"ID": [1, 1, 2, 2, 3, 3], "Activity": ['created', 'completed', 'created', 'completed', 'created',
'rejected'], "state": ['cancelled', 'cancelled', 'finished', 'finished', 'rejected', 'rejected']}
df = pd.DataFrame(data)
df.loc[df['state'] == 'cancelled', 'Activity'] = 'cancelled'
print(df)
ID | Activity | State |
---|---|---|
1 | cancelled | cancelled |
1 | cancelled | cancelled |
2 | created | finished |
2 | completed | finished |
3 | created | rejected |
3 | rejected | rejected |
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.