首页 > 解决方案 > 我如何检查特定列是否具有任何行的相似值,. 一个类似的例子,这种情况是 456 类似于 654

问题描述

我从一个示例数据框开始,并尝试检查该列中任何值的总和对于所有行集是否相同

#### load data###
import pandas as pd
df=pd.DataFrame(iris.data,columns=iris.feature_names)
df.head()

这给了我一个错误“系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。” 并且也不考虑所有行

m=df.shape[0]
columns = [0]


df.iloc[2, :] = [3, 4, 5, 1]
df.iloc[3, :] = [3, 4, 4, 1]

for row1 in range(m-1):
    for row2 in range(row1+1, m):
        if (df.iloc[row1,columns].sum == df.iloc[row2, columns].sum).all():`
            # logic
            print ('Good!')
        else:
            print(f"nothing")

不幸的是,这里的 sum 函数不检查每行,我不确定如何做到这一点

标签: pandasfilterselectionsimilarity

解决方案


Map一个添加数字的函数,然后用于np.where分配'Good!'值的位置duplicated

在:

df = pd.DataFrame({'data': [456,654,235,532,111,354]})

def sum_digits(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

df['status'] = np.where(df.data.map(sum_digits).duplicated(keep=False), 'Good!', 'nothing')

出去:

   data   status
0   456    Good!
1   654    Good!
2   235    Good!
3   532    Good!
4   111  nothing
5   354  nothing

推荐阅读