熊猫:在Dataframe子集上使用iterrows

And*_*ndy 8 python loops subset pandas

使用DataFrame的子集进行iterrows的最佳方法是什么?

我们来看以下简单示例:

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'])
Run Code Online (Sandbox Code Playgroud)

现在我想使用itterrows函数修改此DataFrame的子集,例如:

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

但是,这些变化并不存在.

是否有可能(使用索引'i'进行手动查找除外)对原始Dataframe进行持久更改?

Rom*_*kar 2

为什么需要 iterrows() 呢?我认为在 pandas (或 numpy)中使用矢量化操作总是更好:

df.ix[df['Product'] == 'A', "Product"] = 'A1'
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的评论。这是一个简单的例子,我的实际用例更复杂,我需要在其中使用 iterrows (4认同)