Fabio Lamanna
Fabio Lamanna

Reputation: 21552

Pandas Reindex - Fill Column with Missing Values

I tried several examples of this topic but with no results. I'm reading a DataFrame like:

Code,Counts
10006,5
10011,2
10012,26
10013,20
10014,17
10015,2
10018,2
10019,3

How can I get another DataFrame like:

Code,Counts
10006,5
10007,NaN
10008,NaN
...
10011,2
10012,26
10013,20
10014,17
10015,2
10016,NaN
10017,NaN
10018,2
10019,3

Basically filling the missing values of the 'Code' Column? I tried the df.reindex() method but I can't figure out how it works. Thanks a lot.

Upvotes: 2

Views: 3945

Answers (1)

EdChum
EdChum

Reputation: 393973

I'd set the index to you 'Code' column, then reindex by passing in a new array based on your current index, arange accepts a start and stop param (you need to add 1 to the end) and then reset_index this assumes that your 'Code' values are already sorted:

In [21]:

df.set_index('Code', inplace=True)
df = df.reindex(index = np.arange(df.index[0], df.index[-1] + 1)).reset_index()
df
Out[21]:
     Code  Counts
0   10006       5
1   10007     NaN
2   10008     NaN
3   10009     NaN
4   10010     NaN
5   10011       2
6   10012      26
7   10013      20
8   10014      17
9   10015       2
10  10016     NaN
11  10017     NaN
12  10018       2
13  10019       3

Upvotes: 2

Related Questions