【问题标题】:Concatenate resulting strings from if statements in Python Pandas连接 Python Pandas 中 if 语句的结果字符串
【发布时间】:2021-12-18 05:13:15
【问题描述】:

我对 pandas、python 和 google colab 非常陌生,我刚刚花了 6 个多小时试图找到一种方法来完成我在 2 分钟内在 google 表格中完成的公式。

我想将 if 语句的结果连接到单个列中,就像我在“要修复的问题”列中所做的那样,如果列中出现“是”,则会出现问题,以便工人可以检查需要做什么。

在 Excel 和工作表中,我可以使用“&”加入 if 语句,但每当我尝试使用 pandas 连接时,都会弹出某种错误。我也尝试过使用这种格式的代码:

my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
# Output = 'a,b,c,d'

但它有点旋转数据并弄乱了周围的一切。

我在 google colab 环境中工作,使用 .ipynb 文件。

非常感谢您的关注和帮助。

【问题讨论】:

    标签: python pandas numpy google-colaboratory


    【解决方案1】:

    使用melt:

    out = df.melt(id_vars=['Car Id'], var_name='Things to fix', ignore_index=False) \
            .query("value == 'Yes'").groupby('Car Id')['Things to fix'] \
            .apply(lambda x: ','.join(x.str.extract(r'(\w+)\?', expand=False)))
    
    out = df.merge(out, on='Car Id', how='left')
    

    输出:

    >>> out
       Car Id Problem with Key? Problem with windows? Problem in the engine?       Things to fix
    0    1000               Yes                   Yes                    Yes  Key,windows,engine
    1    1001                No                   Yes                     No             windows
    2    1002                No                    No                     No                 NaN
    

    设置:

    data = {'Car Id': [1000, 1001, 1002],
            'Problem with Key?': ['Yes', 'No', 'No'],
            'Problem with windows?': ['Yes', 'Yes', 'No'],
            'Problem in the engine?': ['Yes', 'No', 'No']}
    
    df = pd.DataFrame(data)
    

    【讨论】:

      【解决方案2】:

      为什么不这样?

      df['tofix'] = df.apply(lambda r: ','.join([r.key*'key',r.win*'win',r.eng*'eng'])
      

      【讨论】:

        猜你喜欢
        • 2016-06-18
        • 2011-11-12
        • 1970-01-01
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        • 2011-10-09
        • 1970-01-01
        相关资源
        最近更新 更多