I want to know which is the best way to update one element in df based on the value of another coulmn in the same dataframe?
p1["price Now"] = df_emptyex["Close"][i]
Above is the code I use to update the colum, but every row got the same value under column "price Now".
And the result will be:
Company | price Now | Value |
---|---|---|
ALFA.ST | 192.421814 | 915.41: |
ASSA-B.ST | 192.421814 | 987.81 |
I want the program to find which row has Company = ASSA-B.ST and update price Now to 200 only on that row like table below:
Company | price Now | Value |
---|---|---|
ALFA.ST | 192.421814 | 915.41: |
ASSA-B.ST | 200 | 987.81 |
CodePudding user response:
Use loc
:
df.loc[df['Company'] == 'ASSA-B.ST', 'price Now'] = 200
# Before
>>> df
Company price Now Value
0 ALFA.ST 192.421814 915.41:
1 ASSA-B.ST 192.421814 987.81
# After
>>> df
Company price Now Value
0 ALFA.ST 192.421814 915.41:
1 ASSA-B.ST 200.000000 987.81
For more information, you can read the Selection by label section on Indexing and selecting data chapter of the user guide.