尝试理解 Pandas 中的 .apply()

2024-02-01

我试图避免循环数据帧,因此最近开始使用 .apply() 。

但是我不太理解这种行为。下面我有一个超级简单的玩具示例。系统会询问用户该列中的每个水果是否都是苹果(它们都是苹果,因此每个答案都是 Y)。

import pandas as pd
df= pd.DataFrame({'fruit':['apple','apple', 'apple','apple', 'apple'],'result':['']*5})
df

   fruit result
0  apple       
1  apple       
2  apple       
3  apple       
4  apple   

设立一个.apply()询问用户水果是否是苹果的函数:

def check_fruit(row):

    # get the current fruit in the row
    current_fruit = row['fruit']

    # print output for user
    print('\n===============================================')
    print('Is this an apple?')
    print('===============================================\n')
    print(f'Current Fruit: {current_fruit}\n')

    # user input - they are asked if the displayed fruit
    # is an apple or not and must enter y/n
    choice = input('Please enter Y/N: ')

     # if they choose yes
    if (choice == 'Y' or choice == 'y'):

        # add the word 'correct' to row column
        row['result']=='Correct'

        return row
    # if they choose no
    elif (choice == 'N' or choice == 'n'):

        # add the word 'Incorrect' to row column
        row['result']=='Incorrect'

        return row

现在应用它 - 注意输出。当数据框中只有 5 行时,为什么 apple 打印了 6 次?

df= df.apply(check_fruit,axis=1)

===============================================
Is this an apple?
===============================================

Current Fruit: apple

Please enter Y/N: y


===============================================
Is this an apple?
===============================================

Current Fruit: apple

Please enter Y/N: y


===============================================
Is this an apple?
===============================================

Current Fruit: apple

Please enter Y/N: y


===============================================
Is this an apple?
===============================================

Current Fruit: apple

Please enter Y/N: y


===============================================
Is this an apple?
===============================================

Current Fruit: apple

Please enter Y/N: y


===============================================
Is this an apple?
===============================================

Current Fruit: apple

Please enter Y/N: y

其次,为什么应用函数没有返回该行?应用该函数后,“结果”列仍然为空。

   fruit result
0  apple       
1  apple       
2  apple       
3  apple       
4  apple

我知道这可能是一件非常明显的事情......

知道我哪里出错了吗?

(ps.我知道输入没有错误检查,现在只关注 .apply() )


请参阅文档pd.DataFrame.apply https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html:

Notes


在当前的实现中 apply 调用func在第一列/行上两次,以确定是否可以采用快速或慢速代码路径。如果出现以下情况,这可能会导致意外行为func有副作用,因为它们会对第一列/行生效两次。

你的职能check_fruit确实有副作用,即要求用户提供一些输入,这种情况发生的次数比您预期的要多。

一般来说,apply和其他数据框架函数旨在与以某种方式转换数据的函数一起使用,而不是与应用程序逻辑一起使用。在这种情况下,如果不显式地写出循环,您不会获得任何特别的好处,因此您能做的最好的事情可能就是手动遍历每一行:

import pandas as pd

def check_fruit(row):
    # ...

df = pd.DataFrame({'fruit': ['apple', 'apple', 'apple', 'apple', 'apple'],
                   'result': [''] * 5})
for row in df.iterrows():
    check_fruit(row)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试理解 Pandas 中的 .apply() 的相关文章

随机推荐