python - 在处理调查数据时,如何合并 pandas 中的列?

标签 python python-3.x pandas dataframe

我有一项调查,我想创建一个包含所有结果的行?

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

enter code here

预期结果(添加另一列) enter image description here

enter image description here

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/

相关文章:

python - 平面内矩形的面积

django - 有没有办法强制django在退出前运行一些整理代码?

python - 将整个函数作为字符串获取/并将字符串转换为函数?

python - 每次我尝试按字符串值过滤数据帧时,我的数据帧都是空的。但是当我尝试从一列中获取计数值时,我得到了数字

Python/Sklearn - 值错误 : could not convert string to float

python - Lambda 包括 if...elif...else

python - 理解 Python 中的 (\D\d)+ 正则表达式模式

python - 如何在不卡住整个代码的情况下在 python 中制作计时器

Python3 - 将每个字符附加到一个字符串(制作一行)

python - 如何通过 python 中的键在循环中命名 pandas 数据帧?