我有一项调查,我想创建一个包含所有结果的行?
survey = pd.DataFrame({
'username':['Mat', 'Ryan', 'Judith', 'John'],
'choice [Website]':['Yes', 'No', 'No', 'No'] ,
'choice [Friend]':['No', 'Yes', 'No', 'No'] ,
'choice [Poster]':['No', 'No', 'Yes', 'No'] ,
'choice [Other]':['No', 'No', 'No', 'Yes'],
})
survey
def how_this_you_find_about_us(patron_answer):
"""
Keyword arguments:
patron_answer-> string : A pandas row
Return:
answer -> : Answer type
"""
if patron_answer['choice [Website]'] == 'Yes':
return 'Website'
elif patron_answer['choice [Friend]'] == 'Yes':
return "Friend"
elif patron_answer['choice [Poster]'] == 'Yes':
return "Poster"
else:
return "Other"
应用函数
survey['answer?'] = survey.apply(lambda x: how_this_you_find_about_us(x))
我在尝试应用该功能时遇到错误
KeyError: ('choice [Website]', 'occurred at index Response ID')
类型
survey.dtypes
username object
choice [Website] object
choice [Friend] object
choice [Poster] object
choice [Other] object
dtype: object
最佳答案
一切正常,除了一件小事:DataFrame.apply
,默认情况下,将函数应用于每一列。
要修复,请将 axis=1
添加到函数调用中。然后,它将函数应用于每一行 ( relevant docs )。
survey['answer?'] = survey.apply(lambda x: how_this_you_find_about_us(x), axis=1)
关于python - 在处理调查数据时,如何合并 pandas 中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56283689/