计算下面的空值数量并将它们放在新的 df 中

Counting number of null values below and placing them in new 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

您可以做的是在数据框的任何列中获取非空条目的索引,然后获取每个条目之间的距离。注意:这是假设它们被很好地排序 and/or 你不介意在你的数据帧上调用 .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)

并且输出将是相同的。