首页 > 解决方案 > 我希望使用 Pandas 从 Python 中的 Power Query M 函数中复制条件列

问题描述

我一直在使用 Power Query 处理一些数据,框架的灵活性给我留下了深刻的印象。目前,我希望在 Pandas 中复制条件列步骤,因为我想将其包含在自动数据清理脚本管道中。

电源查询演示

在这种情况下,Power Query 创建一个名为 acc_col 的新列,查看数据集中的每一列(Tags.1、Tags.2 等),如果该列中的字符串与值的开头 (Acceleration-) 匹配,则它将该值输出到新列中,否则如果找不到匹配项,则输出 Unknown Acc。这是编辑器的外观

 #"Added Conditional Column" = Table.AddColumn(#"Replaced Value", "acc_col", each if Text.StartsWith([Tags.1], "Acceleration-") then [Tags.1] else if Text.StartsWith([Tags.2], "Acceleration-") then [Tags.2] else if Text.StartsWith([Tags.3], "Acceleration-") then [Tags.3] else if Text.StartsWith([Tags.4], "Acceleration-") then [Tags.4] else if Text.StartsWith([Tags.5], "Acceleration-") then [Tags.5] else "Unknown Acc")

我用 Pandas 尝试了一些东西,但我的知识有点有限。我设法使用以下方法阅读了标签列之一

标签0 标签1 标签2
2017年校友,2016年加速 没有任何 没有任何
校友 加速-2017 没有任何
加速-2015 没有任何 没有任何
2017年校友 加速-2015 没有任何
2017年校友 加速-2014 没有任何
df['acc_col'] = df['Tags0'].where(df['Tags0'].str.contains('Acceleration', na=False), )
标签0 标签1 标签2 acc_col
2017年校友,2016年加速 没有任何 没有任何 加速-2016
校友 加速-2017 没有任何 没有任何
加速-2015 没有任何 没有任何 加速-2015
2017年校友 加速-2015 没有任何 没有任何
2017年校友 加速-2014 没有任何 没有任何

我看到输出包含所有包含关键字的内容,但如果我希望对其他列执行相同操作,它会覆盖以前的结果。我需要它们都在同一列上,因为它一一阅读。

 df['acc_col'] = df['Tags1'].where(df['Tags1'].str.contains('Acceleration', na=False), )
标签0 标签1 标签2 acc_col
2017年校友,2016年加速 没有任何 没有任何 没有任何
校友 加速-2017 没有任何 加速-2017
加速-2015 没有任何 没有任何 没有任何
2017年校友 加速-2015 没有任何 加速-2015
2017年校友 加速-2014 没有任何 加速-2014

我觉得我已经很接近了,但我只需要更多帮助。

标签: pythonpandaspowerbipowerquery

解决方案


我想我设法回答了我自己的问题。我只需要将条件的结果添加到另一个pd.where语句并继续,直到我扫描了所有列。

df['Acceleration'] = df['Tags0'].where(df['Tags0'].str.contains('Acceleration', na=False), 
                                                       df['Tags1'].where(df['Tags1'].str.contains('Acceleration', na=False),
                                                       df['Tags2'].where(df['Tags2'].str.contains('Acceleration', na=False),
                                                       df['Tags3'].where(df['Tags3'].str.contains('Acceleration', na=False),
                                                       df['Tags4'].where(df['Tags4'].str.contains('Acceleration', na=False),'Unknown')))))

推荐阅读