我试图避免循环访问数据帧,因此最近开始使用.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行时,为什么苹果要打印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
第二,为什么不从apply函数返回该行?应用该功能后,“结果”列仍为空。
fruit result
0 apple
1 apple
2 apple
3 apple
4 apple
我知道这可能很痛苦……
知道我要去哪里哪里吗?
(ps。我知道输入没有错误检查,现在只关注.apply())
答案 0 :(得分:3)
请参阅pd.DataFrame.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)
答案 1 :(得分:0)
@jdehesa解释了为什么要重复第一行。
我的第二个问题是:为什么不返回新数据。我发现了问题,非常菜鸟的错误。我有row['result']=='Correct'
而不是row['result']='Correct'
,即==
与=
。