有没有一种最佳方法来遍历数据帧的每个单元而不会发生遍历?

时间:2019-01-18 21:43:04

标签: python python-3.x pandas

我想应用一个函数foo(df.column,df.index,df.current value)并以相同的数据帧结束,但是每个单元格以最快的方式等于该函数的结果。

def foo(dates, name, value):
    return black_box_function(dates, name, value)

我希望日期为单元格的列,名称为数据帧单元格内容的索引和值。

我尝试将其实现为df.apply(foo(df['index'], df['column']),但不起作用。

1 个答案:

答案 0 :(得分:0)

您可以使用np.vectorize创建一个矢量化函数,该函数可以将数据框列作为参数(或任何其他类似数组的类型)。请参阅下面的示例 (请注意,传递给矢量化函数的参数的长度必须全部相同):

def foo(val1, val2, val3):
    """ do some stuff in here with your function parameters """
    return val1 * val2 * val3

# this will create a new column in your dataframe called 'new_col'
# each row in df.new_col will be the result of foo applied to that row
df['new_col'] = np.vectorize(foo)(df.col1, df.col2, df.col3)

请参阅np.vectorize的文档。

相关问题