Skip to content Skip to sidebar Skip to footer

Pandas: Use Iterrows On Dataframe Subset

What is the best way to do iterrows with a subset of a DataFrame? Let's take the following simple example: import pandas as pd df = pd.DataFrame({ 'Product': list('AAAABBAA'),

Solution 1:

Why do you need iterrows() for this? I think it's always preferrable to use vectorized operations in pandas (or numpy):

df.ix[df['Product'] == 'A', "Product"] = 'A1'

Solution 2:

I guess the best way that comes to my mind is to generate a new vector with the desired result, where you can loop all you want and then reassign it back to the column

#make a copy of the column
P = df.Product.copy()
#do the operation or loop if you really must
P[ P=="A" ] = "A1"#reassign to original dfdf["Product"] = P

Post a Comment for "Pandas: Use Iterrows On Dataframe Subset"