pythonpandasdataframe

changing a dataframe value based on a unique row value


a bit new to pandas and looking for a possibly better way to solve the following:

given a df where I know a unique value (bb) in a column (A) I want to change the value found in another column (C)

the solution, which I think seems a bit complicated is as follows:

import pandas as pd

df = pd.DataFrame({"A":['aa', 'bb', 'cc'],
                   "B":[1, 1, 1],
                   "C":[1, 88, 1],
                   "D":[1, 1, 1]})

print(df, '\n')

df.at[int(df.loc[df['A']=='bb', 'C'].index.values), 'C'] = 1

print(df)

but I guess there is a simpler way to achieve this?

I guess as this seems quite a basic need that I had hoped to find something more like :

df.at_or_something_else['A'=='bb', 'C']

Solution

  • You can simply use .loc.

    df.loc[df['A']=='bb', 'C'] = 1
    

    For me, the main advantage of .at is that it requires the selection to be only one cell, but if you already know that bb is unique, there's no need to go through the extra legwork.