【问题标题】:Counting the number of insignificant rows in pandas计算熊猫中无关紧要的行数
【发布时间】:2019-12-01 15:33:58
【问题描述】:

我正在尝试计算我的数据集中有多少无关紧要的行。一个无关紧要的行是少于 50% 的列被填充。

count_insignificant_rows=0
for i in range(len(df)):
    columns_empty=0
    for column in df.columns:
        if df[column][i] is np.nan:
            columns_empty=columns_empty+1
            print(columns_empty)
    if columns_empty>=len(df.columns)/2:
        count_insignificant_rows=count_insignificant_rows+1

但是,它一直给我一个关键错误:331

怎么办?

【问题讨论】:

  • 我会添加一列 insignificant 并在该列中计算每一行是否无关紧要。然后,您可以简单地将该列相加得到总数。
  • 上面的评论。因为一旦开始在纯 Python 中循环遍历数据帧,就会破坏 Pandas 的性能。
  • 看看下面的答案,看看他们是否满足你的问题。

标签: python pandas for-loop


【解决方案1】:

每行中非缺失值的第一个计数。

df["insignificant"] = df.apply(lambda x: x.count(), axis=1)
df["insignificant"] = df["insignificant"] / df.shape[1]

然后计算有多少无关紧要的行。

df[df["insignificant"] < 0.5].shape[0]

【讨论】:

    【解决方案2】:

    一种更简单的方法是计算所有具有空值的行:

    # First, create a sample df
    df = pd.DataFrame().from_records(
        [{'id':1,'A':1,'B':1,'C':1,'D':1},
         {'id':2,'A':None,'B':2,'C':2,'D':2},
         {'id':3,'A':None,'B':None, 'C':3,'D':3},
         {'id':4,'A':None,'B':None, 'C':None,'D':4},
         {'id':5,'A':None,'B':None, 'C':None,'D':None}
         ], index = 'id')
    
    # ----
    # Next, drop rows with null values
    # (If your null values are strings, zeros, or infs you can replace them with null values using `.replace()`
    
    # thresh --> drop if this many empty
    thresh = len(df.columns)//2
    sig_rows = len(df.dropna(axis=0, thresh=2))
    print(f'There are {len(df)-sig_rows} insignificant rows.')
    

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 2015-11-29
      • 2019-02-22
      • 1970-01-01
      相关资源
      最近更新 更多