首页 > 解决方案 > 数据框中的矢量化标志分配

问题描述

我有一个数据框,其中包含许多代码的观察结果。我想将一行中存在的代码与列表进行比较。如果该列表中有任何代码,我希望标记该行。我可以使用以下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对所有案例进行评估?有一个更好的方法吗?

标签: pythonpandasnumpyvectorization

解决方案


不使用np.where_.anyany(..)

np.where((df.iloc[:,1:4].isin(code_flags)).any(1),1,0) 

推荐阅读