数据框每一行的熊猫调用函数

时间:2019-02-12 15:29:26

标签: pandas

我有一个这样的熊猫数据框:

CUR_MONTH   PREV_MONTH
Jan            Dec
Dec             Nov
Nov            Oct

我需要调用一个接受两个参数CUR_MONTH和PREV_MONTH的函数。如何为数据帧的每一行循环调用该函数?

1 个答案:

答案 0 :(得分:0)

这将在数据框中以列的形式返回函数的行级别计算

for index, row in your_dataframe.iterrows():
   row_level_calculation = your_function(row['CUR_MONTH'], row['PREV_MONTH'])
   your_dataframe.loc[index, 'new_column_with_calculation'] = row_level_calculation

为了提高速度,您还可以通过这样设置函数来避免循环。

def row_calculation(row):
    current_month = row['CUR_MONTH']
    previous_month = row['PREV_MONTH']
    generic_calculation = concat(current_month + previous_month)
    return(generic_calculation)

your_dataframe['new_column_with_calculation'] = your_dataframe.apply(row_calculation, axis = 1)