Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Panda's .at function to modify multiple rows

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?

like image 289
wrong_path Avatar asked May 08 '19 19:05

wrong_path


People also ask

How can I change multiple row values in Pandas?

To replace multiple values in a DataFrame, you can use DataFrame. replace() method with a dictionary of different replacements passed as argument.

How do I change Dtypes of multiple columns in Pandas?

You can use df. astype() with a dictionary for the columns you want to change with the corresponding dtype.

Which method in Pandas can be used to add multiple rows to a DataFrame?

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.


1 Answers

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.

like image 194
secretive Avatar answered Sep 28 '22 07:09

secretive