How to efficiently insert multiple rows to a pandas DF with a missing value?

Question:

I have a DF:

df = pd.DataFrame({"A":[0,1,3,5,6], "B":['B0','B1','B3','B5','B6'], "C":['C0','C1','C3','C5','C6']})

I’m trying to insert 10 empty rows at the position where the number is missed from the continuous sequence of column A. For the 10 rows, values of column A, B and C’s are the missed number, Nan, and Nan, respectively. Like this:

A   B   C
0   B0  C0
1   B1  C1
2   NaN NaN
2   NaN NaN
2   NaN NaN
2   NaN NaN
2   NaN NaN
2   NaN NaN
2   NaN NaN
2   NaN NaN
2   NaN NaN
2   NaN NaN
3   B3  C3
4   NaN NaN
4   NaN NaN
4   NaN NaN
4   NaN NaN
4   NaN NaN
4   NaN NaN
4   NaN NaN
4   NaN NaN
4   NaN NaN
4   NaN NaN
5   B5  C5
6   B6  C6

I’ve played with index, but this adds only 1 row:

df1 = df.merge(how='right', on='A', right = pd.DataFrame({'A':np.arange(df.iloc[0]['A'],
                                                                        df.iloc[-1]['A']+1)})).reset_index().drop(['index'], axis=1)

Thanks in advance!

Asked By: dramarama

||

Answers:

One approach could be as follows:

  • First, use df.set_index to make column A the index.
  • Next, use range for a range that runs from 0 through to the max of A (i.e. 6).
  • Now, apply df.reindex based on np.repeat. We use a loop to feed a 1 to the repeats parameter for all the values that exist in A, for all the ones that are missing, we use 10.
  • Finally, chain df.reset_index.
df.set_index('A', inplace=True)
rng = range(df.index.max()+1)
df = df.reindex(np.repeat(rng,[1 if i in df.index else 10 for i in rng]))
    .reset_index(drop=False)

print(df)

    A    B    C
0   0   B0   C0
1   1   B1   C1
2   2  NaN  NaN
3   2  NaN  NaN
4   2  NaN  NaN
5   2  NaN  NaN
6   2  NaN  NaN
7   2  NaN  NaN
8   2  NaN  NaN
9   2  NaN  NaN
10  2  NaN  NaN
11  2  NaN  NaN
12  3   B3   C3
13  4  NaN  NaN
14  4  NaN  NaN
15  4  NaN  NaN
16  4  NaN  NaN
17  4  NaN  NaN
18  4  NaN  NaN
19  4  NaN  NaN
20  4  NaN  NaN
21  4  NaN  NaN
22  4  NaN  NaN
23  5   B5   C5
24  6   B6   C6
Answered By: ouroboros1

Let’s try to repeat the indices where the values diff is above 1 and concat:

N = 10
out = (pd.concat([df, df[['A']].loc[df.index.repeat(df['A'].diff(-1).lt(-1).mul(N-1))]])
         .sort_index(kind='stable')
      )

Output:

   A    B    C
0  0   B0   C0
1  1   B1   C1
1  1  NaN  NaN
1  1  NaN  NaN
1  1  NaN  NaN
1  1  NaN  NaN
1  1  NaN  NaN
1  1  NaN  NaN
1  1  NaN  NaN
1  1  NaN  NaN
1  1  NaN  NaN
2  3   B3   C3
2  3  NaN  NaN
2  3  NaN  NaN
2  3  NaN  NaN
2  3  NaN  NaN
2  3  NaN  NaN
2  3  NaN  NaN
2  3  NaN  NaN
2  3  NaN  NaN
2  3  NaN  NaN
3  5   B5   C5
4  6   B6   C6
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.