I'm a little bit confused with the usage of at
. From the website:
Access a single value for a row/column label pair.
Nonetheless, I can still use it to change values in multiple rows. For instance:
df = pd.DataFrame([[0, 2, 3], [0, 2, 1], [10, 20, 30]], index=[0, 1, 2], columns=['A', 'B', 'C'])
A B C
0 0 2 3
1 0 2 1
2 10 20 30
idxs = df[df.B==2].index.values
df.at[idxs, 'A'] = -33
A B C
0 -33 2 3
1 -33 2 1
2 10 20 30
This will in fact change the values in both the first two rows (column A
).
Am I doing something wrong? Is it safe using at
to change multiple rows this way?
To replace multiple values in a DataFrame, you can use DataFrame. replace() method with a dictionary of different replacements passed as argument.
You can use df. astype() with a dictionary for the columns you want to change with the corresponding dtype.
We can also add multiple rows using the pandas. concat() by creating a new dataframe of all the rows that we need to add and then appending this dataframe to the original dataframe.
Technically, .at is accessing single value for a row/column label pair and changing it one at a time. But your variable idxs is a list so it is executed for every index in the list. So the answer to your question is no, you are doing nothing wrong and yes, it is perfectly safe to use .at to change multiple rows this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With