ashish kumar ashish kumar - 4 years ago 65
Python Question

How to generate values in a range continuously?

I have a

Dataset
which I need to modify using pandas. Below is the detail of the particular column I need to work on:

df["Dependents"].value_counts()

0 345

1 102

2 101

3+ 51

Name: Dependents, dtype: int64

df["Dependents"].notnull().value_counts()

True 599

False 15

Name: Dependents, dtype: int64


I need to assign the
null
values as
0
,
1
or
2
one by one. Like if for first row, I assign
0
, then next row should be
1
and then the next
2
. Then again start from
0
until all
null
values are filled.

How can I achieve it?

Answer Source

IIUC you can do it this way:

assuming you have the following DF:

In [214]: df
Out[214]:
   Dependents
0         NaN
1           0
2           0
3           0
4         NaN
5           1
6         NaN
7          3+
8         NaN
9          3+
10          2
11         3+
12          1
13        NaN

Solution:

In [215]: idx = df.index[df.Dependents.isnull()]

In [216]: idx
Out[216]: Int64Index([0, 4, 6, 8, 13], dtype='int64')

In [217]: df.loc[idx, 'Dependents'] = np.take(list('012'), [x%3 for x in range(len(idx))])

In [218]: df
Out[218]:
   Dependents
0           0
1           0
2           0
3           0
4           1
5           1
6           2
7          3+
8           0
9          3+
10          2
11         3+
12          1
13          1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download