Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'),
  'Quantity': [5,2,5,10,1,5,2,3],
  'Start' : [
      DT.datetime(2013,1,1,9,0),
      DT.datetime(2013,1,1,8,5),
      DT.datetime(2013,2,5,14,0),
      DT.datetime(2013,2,5,16,0),
      DT.datetime(2013,2,8,20,0),                                      
      DT.datetime(2013,2,8,16,50),
      DT.datetime(2013,2,8,7,0),
      DT.datetime(2013,7,4,8,0)]})

df = df.set_index(['Start'])

Now I would like to modify a subset of this DataFrame using the itterrows function, e.g.:

for i, row_i in df[df.Product == 'A'].iterrows():
    row_i['Product'] = 'A1' # actually a more complex calculation

However, the changes do not persist.

Is there any possibility (except a manual lookup using the index 'i') to make persistent changes on the original Dataframe ?

like image 899
Andy Avatar asked Oct 29 '13 18:10

Andy


1 Answers

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'
like image 181
Roman Pekar Avatar answered Nov 19 '22 18:11

Roman Pekar