新的Dataframe列作为其他行(熊猫)的通用函数

保利

在中创建 DataFrame 其他列中 最快的列的最快(最有效)方法pandas 什么?

考虑以下示例:

import pandas as pd

d = {
    'id': [1, 2, 3, 4, 5, 6],
    'word': ['cat', 'hat', 'hag', 'hog', 'dog', 'elephant']
}
pandas_df = pd.DataFrame(d)

产生:

   id word
0   1  cat
1   2  hat
2   3  hag
3   4  hog
4   5  dog
5   6  elephant

假设我想创建一个新列,bar其中包含一个值,该值基于使用函数foo将当前行中的单词与中的其他行进行比较的输出而得出dataframe

def foo(word1, word2):
    # do some calculation
    return foobar  # in this example, the return type is numeric

threshold = some_threshold

for index, _id, word in pandas_df.itertuples():
    value = sum(
        pandas_df[pandas_df['word'] != word].apply(
            lambda x: foo(x['word'], word),
            axis=1
        ) < threshold
    )
    pandas_df.loc[index, 'bar'] = value

这的确产生了正确的输出,但是它使用了itertuples()and apply(),这对于large而言并不是很有效DataFrames

有没有一种方法可以矢量化(这是正确的术语?)这种方法?还是有另一种更好(更快)的方法来做到这一点?

注释/更新:

  1. 在原始帖子中,我使用了“编辑距离/左手脚距”作为foo函数。我改变了这个问题,试图变得更通用。想法是要应用的功能是将当前行的值与所有其他行进行比较,并返回一些汇总值。

如果foowasnltk.metrics.distance.edit_distance和thethreshold被设置为2(如原始文章中所示),则会产生以下输出:

   id word        bar
0   1  cat        1.0
1   2  hat        2.0
2   3  hag        2.0
3   4  hog        2.0
4   5  dog        1.0
5   6  elephant   0.0
  1. 我也有同样的问题spark dataframes为好。我认为将这些分成两个职位是很有意义的,因此它们的范围不太广。但是,我通常发现,pandas有时可以修改类似问题的解决方案以使其适用spark

  2. 灵感来自这个答案我的spark版本这个问题,我试图用一个笛卡尔积pandas我的速度测试表明速度稍快(尽管我怀疑这可能随数据大小而变化)。不幸的是,我仍然无法拨通电话apply()

示例代码:

from nltk.metrics.distance import edit_distance as edit_dist

pandas_df2 = pd.DataFrame(d)

i, j = np.where(np.ones((len(pandas_df2), len(pandas_df2))))
cart = pandas_df2.iloc[i].reset_index(drop=True).join(
    pandas_df2.iloc[j].reset_index(drop=True), rsuffix='_r'
)

cart['dist'] = cart.apply(lambda x: edit_dist(x['word'], x['word_r']), axis=1)
pandas_df2 = (
    cart[cart['dist'] < 2].groupby(['id', 'word']).count()['dist'] - 1
).reset_index()
Qusai Alothman

让我们尝试分析一下问题:

如果有N行,则N*N在相似性函数中要考虑“对”。在一般情况下,对所有这些元素进行评估都是无可避免的(听起来很合理,但我无法证明这一点)。因此,您至少具有O(n ^ 2)个时间复杂度

但是,您可以尝试使用时间复杂度恒定的因素我发现的可能选项是:


1.并行化:

由于您有一些大型的DataFrame,并行处理是最佳的选择。这将使您(几乎)在时间复杂度方面得到线性改善,因此,如果您有16名工作人员,您将获得(几乎)16倍的改进。

例如,我们可以将的行划分df为不相交的部分,并分别处理每个部分,然后合并结果。一个非常基本的并行代码可能看起来像这样:

from multiprocessing import cpu_count,Pool

def work(part):
    """
    Args:
        part (DataFrame) : a part (collection of rows) of the whole DataFrame.

    Returns:
        DataFrame: the same part, with the desired property calculated and added as a new column
    """
     # Note that we are using the original df (pandas_df) as a global variable
     # But changes made in this function will not be global (a side effect of using multiprocessing).
    for index, _id, word in part.itertuples(): # iterate over the "part" tuples
        value = sum(
            pandas_df[pandas_df['word'] != word].apply( # Calculate the desired function using the whole original df
                lambda x: foo(x['word'], word),
                axis=1
            ) < threshold
        )
        part.loc[index, 'bar'] = value
    return part

# New code starts here ...

cores = cpu_count() #Number of CPU cores on your system

data_split = np.array_split(data, cores) # Split the DataFrame into parts
pool = Pool(cores) # Create a new thread pool
new_parts = pool.map(work , data_split) # apply the function `work` to each part, this will give you a list of the new parts
pool.close() # close the pool
pool.join()
new_df = pd.concat(new_parts) # Concatenate the new parts

注意:我试图使代码尽可能接近OP的代码。这只是一个基本的演示代码,并且存在许多更好的替代方法。


2.“低级”优化:

另一个解决方案是尝试优化相似度函数的计算和迭代/映射。与上一个或下一个选项相比,我认为这不会使您获得更多的加速。


3.取决于功能的修剪:

您可以尝试的最后一件事是依赖相似功能的改进。这在一般情况下不起作用,但如果您可以分析相似性函数,则将很好地工作。例如:

假设您使用的是Levenshtein距离(LD),则可以观察到任意两个字符串之间的距离> ==长度之间的差。LD(s1,s2) >= abs(len(s1)-len(s2))

您可以使用此观察结果来修剪可能的相似对,以进行评估。因此,对于每个字符串长度l1,只有具有长度的字符串比较它l2abs(l1-l2) <= limit(限制为所接受的最大相似度,在您提供的示例中为2)。

另一个观察是LD(s1,s2) = LD(s2,s1)这样可以将对数减少2倍。

该解决方案实际上可能使您陷入O(n)时间复杂性(高度依赖于数据)的问题。
为什么?你可能会问。
这是因为,如果我们有10^9行,但平均而言10^3,每行只有“接近”长度的行,那么我们需要对函数进行约10^9 * 10^3 /2对运算,而不是10^9 * 10^9成对运算。但这(再次)取决于数据。如果(在此示例中)您拥有长度均为3的字符串,则此方法将无用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

新列作为其他列的总和

计算新列作为其他列熊猫的平均值

将函数应用于以其他列作为参数的熊猫列

创建一个新的数据框列作为其他列的函数

新列作为其他列的列表,但没有 nans

使用其他列作为summary_at()中函数的参数

熊猫数据框使用列作为行

Python:使用其他列将值分配给Pandas中的新列作为列表

创建一个新列作为 R 中其他列中的最小值

从 R 中的现有列值创建新列(使用其他列作为键)

如何将字典的特定列作为python中其他函数的输入传递

使用dplyr折叠以其他数字列作为条件的行

将列表或系列作为一行附加到熊猫DataFrame吗?

熊猫根据其他行的总和/差异添加新行

将新列作为行的函数添加到 Numpy Array

如何应用使用多列作为熊猫输入的函数?

如何从表中选择特定行,其中一列作为其他行的值之和?

在熊猫DataFrame中用其他文本连接行

Javascript新行函数不会呈现其他Javascript函数

熊猫数据框使用列作为行(融化)

在 ng-repeat 其他函数中添加新行

groupby 1列和其他列的总和作为新的数据框熊猫

添加新列作为两行之间的差异

合并两个熊猫列作为索引,以其列名作为值创建新列

熊猫-根据其他行选择行

熊猫:根据其他行删除行

熊猫-根据其他行中的相对值计算新的列

根据其他列中给出的值在熊猫数据框上生成 n 数量的新行

根据其他df和熊猫的条件,在df中添加新行