python - 我希望使用 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 |
我觉得我已经很接近了,但我只需要更多帮助。
解决方案
我想我设法回答了我自己的问题。我只需要将条件的结果添加到另一个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')))))
推荐阅读
- c++ - 打破 While 循环 C++
- javascript - 如何在 React 中从非 React 库中渲染 div 对象?
- git - 将分支恢复到旧位置的最佳方法是什么?
- xml - 修改python-docx中paragraph.style._element.xml中的XML
- javascript - 我想使用 document.getElementByID 自动填充网络表单,但是每当我返回网站时,ID 都会不断变化
- sql - 如何列出 Teradata 中所有定义的宏?
- laravel-5.8 - 如何扩展 FaCuZ/laravel 主题中的布局?
- javascript - 将子组件中的文本字段链接到 VueJS 中父组件的道具
- android - 可以在打印 logcat 之前获取日志吗?
- kubernetes - 在 helm kubernetes 中使用 secret 存储敏感数据