pandas :在数据框子集上使用迭代 [英] Pandas: Use iterrows on Dataframe subset

查看:59
本文介绍了 pandas :在数据框子集上使用迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'])

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

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.

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

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

推荐答案

为什么为此需要iterrows()?我认为在熊猫(或numpy)中使用向量化运算始终是可取的:

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'

这篇关于 pandas :在数据框子集上使用迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆