【问题标题】:Pandas: Use iterrows on Dataframe subsetPandas:在 Dataframe 子集上使用 iterrows
【发布时间】:2013-11-09 01:55:20
【问题描述】:

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

让我们举个简单的例子:

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 的一个子集,例如:

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

但是,更改不会持续存在。

是否有任何可能(使用索引“i”进行手动查找除外)对原始数据帧进行持久更改?

【问题讨论】:

  • 您是否尝试通过从不同列获取参数来将函数应用于每一行?这已经是answered here

标签: python loops pandas subset


【解决方案1】:

我想我想到的最好方法是生成一个具有所需结果的新向量,您可以在其中循环所有想要的内容,然后将其重新分配回列

#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 df
df["Product"] = P

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的评论。这是一个简单的例子,我的实际用例更复杂,我需要在其中使用 iterrows
    • @Andy:那么你想在你的问题中说清楚
    猜你喜欢
    • 2022-12-22
    • 2023-03-03
    • 2014-08-08
    • 2016-11-04
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2016-06-21
    相关资源
    最近更新 更多