【问题标题】:Alternative to iterating dataframe while keeping track of the current index在跟踪当前索引的同时迭代数据框的替代方法
【发布时间】:2021-12-24 20:56:14
【问题描述】:

我正在处理大型数据帧,并注意到使用df.iterrows() 遍历每个数据帧需要很长时间。目前,我遍历数据帧的行,提取数据帧中某些行的值并将它们乘以一些预定义的权重。然后我创建一个置信水平,如果它大于某个阈值,我将索引添加到列表indices。这是我的意思的一个简单示例:

import pandas as pd

attributes = ['attr1', 'attr2', 'attr3']
d = {'attr1': [1, 2], 'attr2': [3, 4], 'attr3' : [5, 6], 'meta': ['foo', 'bar']}
df = pd.DataFrame(data=d)

indices = []
threshold = 0.5
for index, row in df.iterrows():
  weights = [0.3 , 0.3, 0.4]
  results = []
  for attr in attributes:
    if attr == 'attr1':
      results.append(row[attr] * 5)
    else:
      results.append(row[attr])
  confidence_level = sum(list(map(lambda x, y: x * y, results, weights))) / len(results)
  if confidence_level >= threshold:
    indices.append(index)

我的问题是,是否有办法摆脱第一个循环,同时仍跟踪数据框中的索引?如果可能,内部循环应该保持原样,因为它包含一个条件。

【问题讨论】:

    标签: python pandas dataframe iteration


    【解决方案1】:

    这是完全可矢量化的:

    weighted_attrs = df[attributes] * weights / len(weights)
    # honestly, it'd be more logical to adjust weights instead
    weighted_attrs['attr1'] *= 5
    confidence_levels = weighted_attrs.sum(axis=1)
    indices = df.index[confidence_levels > threshold]
    

    【讨论】:

    • 感谢您的回答。是否可以将我的情况纳入建议的解决方案?
    • @DeepLearningEel 更新了答案。
    【解决方案2】:

    遍历 panda 数据帧确实很慢,应该避免。您可以使用 df.apply() 为每一行应用一个函数。如果您这样做是为了获取每行的置信度并仅选择置信度高于阈值的行,您应该会得到您想要的。

    【讨论】:

    • 你有例子吗?
    猜你喜欢
    • 2016-07-10
    • 1970-01-01
    • 2020-05-02
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2016-04-07
    相关资源
    最近更新 更多