【问题标题】:how can i check if almost all rows are identical and if so then verify that the final differing row varies by some constant k我如何检查几乎所有行是否相同,如果是,则验证最终不同的行是否有一些常数 k
【发布时间】:2020-02-03 06:56:40
【问题描述】:

使用尺寸为 (150,4) 的 iris 数据集我想查看第 1、2 和 4 列中的行是否相同,如果是,则验证第 3 列的值是否相差某个常数 k。这必须针对每个可能的行组合进行。

#### 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()。”并且也不考虑所有行

我这里选择了k=4

list=range(0,148)

for row in list:
    if df.iloc[row,:]==df.iloc[row+1,:]:
        df.iloc[row,2]-df.iloc[row+1,2]<=4
    else:
        print('nothing')

【问题讨论】:

    标签: python pandas comparison filtering rows


    【解决方案1】:

    首先,您需要过滤要比较的列。在这种情况下,第 0、1 和 3 列通过执行以下比较 df.iloc[row1,[0, 1, 3]] == df.iloc[row2, [0, 1, 3]]。这将返回 True 或 False 值的数组。但是您需要 all 列相同。要实现这一点,您需要 .all() 方法。只有当数组中的所有值都为 True 时,它​​才会返回 true。总结:

    if (df.iloc[row1,identical_columns] == df.iloc[row2, identical_columns]).all():
    

    而且由于您需要遍历每个可能的行组合,因此双 for 循环会做得很好。

    for row1 in range(m-1):
        for row2 in range(row1+1, m):
            # Check for every row combinaton if the columns are equal
            if (df.iloc[row1,identical_columns] == df.iloc[row2, identical_columns]).all():
                pass
    

    总共:

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame(data=np.random.randint(0, 100, (10, 4)))
    m = df.shape[0]
    
    identical_columns = [0, 1, 3]
    k = 4
    
    # Force rows values to pass
    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):
            # Check for every row combinaton if the columns are equal
            if (df.iloc[row1,identical_columns] == df.iloc[row2, identical_columns]).all():
    
    
                if df.iloc[row1,2] - df.iloc[row2,2] <= k:
                    # TODO: Implement Your logic
                    print ('We pass!')
            else:
                print(f"row {row1} and row {row2} don't pass")
    

    【讨论】:

      【解决方案2】:

      错误信息基本上告诉你如何解决这个问题:

      if df.iloc[row,:]==df.iloc[row+1,:]:
      

      必须是:

      if (df.iloc[row,:]==df.iloc[row+1,:]).all():
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-12
        • 2021-05-21
        • 2021-10-29
        • 1970-01-01
        • 2020-10-27
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多