【问题标题】:Is there any reliable way to define and cal functions on dataframe in Python是否有任何可靠的方法可以在 Python 中的数据帧上定义和校准函数
【发布时间】:2019-05-13 10:32:25
【问题描述】:

我有一个包含消费者电子邮件数据的数据框 - 新的和重复的联系电子邮件。我需要根据某些条件在这个数据中找出异常值:

  • 条件 1:count1 > 1count 2 > 1
  • 条件 2:count1 > 1count 2 < 1

我已经检查了函数定义,python 中的语法,并相应地定义了一个用于异常值分类的函数。

def outlier():
    for index, row in df.iterrows():
        if([row][count1] > 1 and [row][count2] > 1):
            if(df[row][Journey] == df[row][journey_lag]):
                df[row][outlier] = Same_Property/Date/Agent/Journey
            else:
            df[row][outlier] = Same_Property/Date/Agent-Different Journey
        elif([row][count1] > 1 and [row][count2] == 1):
            if(df[row][Journey] == df[row][journey_lag]):
                df[row][outlier] = Same_Property/Date-Different_Agent/Journey
            else:
                df[row][outlier]=Same_Property/Date_Different_Agent/Journey
return df 

我希望使用以下数据框执行此功能:

df.outlier
df.apply(outlier)

错误:无法获得 reqd 结果

【问题讨论】:

  • 如果您想将数据与apply (doc) 一起使用,您需要在outlier 函数中传递要处理的数据。如果您对行或列进行迭代,则可以使用 axis 参数选择行或列。然后你可以在第二行应用它:df.apply(outlier)

标签: python-3.x function dataframe for-loop if-statement


【解决方案1】:

当您在DataFrame 对象上使用.apply(my_function) 时,pandas 将期望一个单参数函数,如果axis=0,此参数将是DataFrame 的一列,如果axis=1 是DataFrame 的一行。

你需要这样的东西:

def outlier(row):
    if row['count1'] > 1 and row['count2'] > 1:
        if row['Journey'] == row['journey_lag']:
            return 'Same_Property/Date/Agent/Journey'
        else:
            return 'Same_Property/Date/Agent/Different_Journey'
    elif row['count1'] > 1 and row['count2'] == 1:
        if row['Journey'] == row['journey_lag']:
            return 'Same_Property/Date/Different_Agent/Journey'
        else:
            return 'Same_Property/Date/Different_Agent/Different_Journey'

df['outlier'] = df.apply(outlier, axis=1)

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 2012-10-10
    • 1970-01-01
    • 2018-06-09
    • 2020-12-09
    • 2012-03-21
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多