首页 > 解决方案 > 计算下面的空值数量并将它们放在新的df中

问题描述

df

我正在尝试计算数据框中每个非空单元格下方的空值数量,并将该数字放入新变量(大小)和数据框中。

我已经包含了我要计算的数据框的图片。我现在只对到达日期栏感兴趣。新的数据框应该有一列包含 1,1,3,7..etc 作为它的第一个观察值。

##Loops through all of rows in DOAs
for i in range(0, DOAs.shape[0]):
    j=0
    if DOAs.iloc[int(i),3] != None: ### the rest only runs if the current, i, observation isn't null
        newDOAs.iloc[int(j),0] = DOAs.iloc[int(i),3] ## sets the jth i in the new dataframe to the ith (currently assessed) row of the old
        foundNull = True #Sets foundNull equal to true
        k=1 ## sets the counter of people 
        while foundNull == True and (k+i) < 677: 
                if DOAs.iloc[int(i+k),3] == None: ### if the next one it looks at is null, increment the counter to add another person to the family
                    k = k+1
                else:
                    newDOAs.iloc[int(j),1] = k ## sets second column in new dataframe equal to the size
                    j = j+1
                    foundNull = False
    j=0

标签: pythonpython-3.xloopsfor-loopdataframe

解决方案


您可以做的是在数据框的任何列中获取非空条目的索引,然后获取每个条目之间的距离。注意:这是假设它们排列整齐和/或您不介意调用.reset_index()您的数据框。

这是一个示例:

df = pd.DataFrame({'a': [1, None, None, None, 2, None, None, 3, None, None]})
not_null_index = df.dropna(subset=['a']).index
null_counts = {}

for i in range(len(not_null_index)):
    if i < len(not_null_index) - 1:
        null_counts[not_null_index[i]] = not_null_index[i + 1] - 1 - not_null_index[i]
    else:
        null_counts[not_null_index[i]] = len(df.a) - 1 - not_null_index[i]

null_counts_df = pd.DataFrame({'nulls': list(null_counts.values())}, index=null_counts.keys())
df_with_null_counts = pd.merge(df, null_counts_df, left_index=True, right_index=True)

本质上,这段代码所做的只是获取数据帧中非空值的索引,然后获取每个索引与下一个非空索引之间的差异并将其放入列中。然后null_counts将它们粘贴在数据框中并将其与原始数据合并。

运行此代码段后,df_with_null_counts等于:

     a  nulls
0  1.0      3
4  2.0      2
7  3.0      2

或者,您可以使用 numpy 而不是使用循环,这对于大型数据帧会快得多。这是一个示例:

df = pd.DataFrame({'a': [1, None, None, None, 2, None, None, 3, None, None]})
not_null_index = df.dropna(subset=['a']).index

offset_index = np.array([*not_null_index[1:], len(df.a)])
null_counts = offset_index - np.array(not_null_index) - 1

null_counts_df = pd.DataFrame({'nulls': null_counts}, index=not_null_index)
df_with_null_counts = pd.merge(df, null_counts_df, left_index=True, right_index=True)

并且输出将是相同的。


推荐阅读