python - 在此示例中避免使用 iterrows 的好方法是什么?

标签 python pandas

我讨论了 iterrows 的性能问题 previously , 并得到了良好的普遍 react 。这个问题是一个特定的案例,我希望你能帮助我更好地应用一些东西,因为 iterrows 很慢。

我相信这个问题对任何感觉被困在行迭代思维中的新 python/pandas 程序员都是有用的。

我看到的使用“ map ”或“应用”的示例通常显示一个看起来足够直观的数据表。但是,我正在处理两个表并且它们很大(T1 是 250 万行,T2 是 96000 行)。

这是一个简单的示例(它在我的 session 中有效):

import pandas as pd
import numpy as np

# Create the original tables
t1 = {'letter':['a','b'],
      'number1':[50,-10]}

t2 = {'letter':['a','a','b','b'],
      'number2':[0.2,0.5,0.1,0.4]}

table1 = pd.DataFrame(t1)
table2 = pd.DataFrame(t2)

# Create the body of the new table
table3 = pd.DataFrame(np.nan, columns=['letter','number2'], index=[0])

# Iterate through filtering relevant data, optimizing, returning info
for row_index, row in table1.iterrows():   
    t2info = table2[table2.letter == row['letter']].reset_index()
    table3.ix[row_index,] = optimize(t2info,row['number1'])

# Define optimization
def optimize(t2info, t1info):
    calculation = []
    for index, r in t2info.iterrows():
        calculation.append(r['number2']*t1info)
    maxrow = calculation.index(max(calculation))
    return t2info.ix[maxrow]

print table3

输出是:

  letter number2
0      a     0.5
1      b     0.1

[2 rows x 2 columns]

总体思路:

  1. 生成表 3 是目标 - 它具有与表 1 相同的维度
  2. 根据表 1 中的相应输入,用表 2 中的“最佳”行填充表 3。
  3. 表 2 中使用的数据是基于表 1 中“字母”的子集

(显然,这种情况并不慢,因为它很小,但是当处理数百万行时它很慢。请记住,在实际示例中,我在两个表中都有更多列。)

最佳答案

对我来说,看起来最简单的事情是合并 letter 然后 groupby

import pandas as pd
import numpy as np

# Create the original tables
t1 = {'letter':['a','b'],
      'number1':[50,-10]}

t2 = {'letter':['a','a','b','b'],
      'number2':[0.2,0.5,0.1,0.4]}

table1 = pd.DataFrame(t1)
table2 = pd.DataFrame(t2)

table3 = table1.merge(table2,on='letter')

grouped = table3.groupby('letter')

def get_optimization(df):
    product_column = df.number1 * df.number2
    idx_of_prod_col_max = product_columns.idxmax()
    return_val = df.ix[idx_of_prod_col_max]['number2']
    return return_val

table3 = grouped.apply(get_optimization)

关于python - 在此示例中避免使用 iterrows 的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24875096/

相关文章:

python - 在Python中按月对日期时间对象进行分组

python - 当一个系列被传递给 Numpy exp() 函数时,为什么会返回一个系列?

python - SQL iPython Magic 扩展不会加载

python - 单击图像1次,获取位置并销毁OpenCv窗口

python - 这两个Python代码的时间复杂度差异是多少?

python - 让外籍人士在 python 中使用 .dtd 进行实体替换

python - 将日期时间转换为统一的 15 分钟格式,并从日期时间中提取年、月、日、小时列

Python 3 使用 pliSTLib 解析 iTunes 库 plist 文件

Python错误: 'numpy.bool_' object is not iterable

python - 将 Pandas (python)数据帧序列化为二进制格式