python - 数据框中的矢量化标志分配
问题描述
我有一个数据框,其中包含许多代码的观察结果。我想将一行中存在的代码与列表进行比较。如果该列表中有任何代码,我希望标记该行。我可以使用以下itertuples
方法完成此操作:
import pandas as pd
import numpy as np
df = pd.DataFrame({ 'id' : [1,2,3,4,5],
'cd1' : ['abc1', 'abc2', 'abc3','abc4','abc5'],
'cd2' : ['abc3','abc4','abc5','abc6',''],
'cd3' : ['abc10', '', '', '','']})
code_flags = ['abc1','abc6']
# initialize flag column
df['flag'] = 0
# itertuples method
for row in df.itertuples():
if any(df.iloc[row.Index, 1:4].isin(code_flags)):
df.at[row.Index, 'flag'] = 1
输出正确地添加了flag
带有适当标志的列,其中 1 表示已标记的条目。
但是,在我的实际用例中,这需要几个小时才能完成。我尝试使用numpy.where
.
df['flag'] = 0 # reset
df['flag'] = np.where(any(df.iloc[:,1:4].isin(code_flags)),1,0)
这似乎对一切的评价都是一样的。我想我对矢量化如何处理索引感到困惑。我可以删除分号并写入df.iloc[1:4]
并获得相同的结果。
我误解了这个where
功能吗?我的索引是否不正确并导致True
对所有案例进行评估?有一个更好的方法吗?
解决方案
不使用np.where
_.any
any(..)
np.where((df.iloc[:,1:4].isin(code_flags)).any(1),1,0)
推荐阅读
- flutter - StreamBuilder 仅显示第二个 MergeStream 元素的结果
- python - 需要帮助重新调整 NASDAQ IPO API 无法在 Python 中运行
- c# - 为什么我的 C# 在 SharePoint 上找不到任何列表?
- user-interface - 如何在 Fyne 中将窗口大小调整为对话框大小
- android - 回收站视图未在 Fragment (Android) 上显示项目
- npm - 终端卡住,npm install 后无法输入 git 命令
- python - 如何在pycharm中清除屏幕
- c# - 不支持使用 let 关键字的 Entity Framework Core 5?
- css - RStudio Connect 在更新时将 CSS 粘贴到单元格中
- c++ - OpenCL 内核删除所需的时间