range(1:len(df)) assigns NaN to last rows in dataframe

Viewed 258

I have this weird problem with my code . I am trying to generate Auto Id to my dataframe with this code

df['id'] = pd.Series(range(1,(len(df)+1))).astype(str).apply('{:0>8}'.format

now, len(df) is equals to 799734 but df['id'] is Nan after row 77998

I tried to print the values using:

[print(i) for i in range(1,(len(df)+1))]

In first attempt it printed None after 77998 values. In second attempt it printed all values to the end normally. but dataframe has still Nan in last rows.

May be it has something to do with memory? I am not getting any hint. Please help me solve this issue.

1 Answers

Missing values means there is different index values in Series and DataFrame, for correct working need same.

So need pass df.index to Series constructor:

df['id'] = pd.Series(range(1,(len(df)+1)), index=df.index).astype(str).apply('{:0>8}'.format

Or 2 rows solution with assign range:

df['id'] = range(1,(len(df)+1))
df['id'] = df['id'].astype(str).apply('{:0>8}'.format

Or create default index values in DataFrame for same like Series:

df = df.reset_index(drop=True)
df['id'] = pd.Series(range(1,(len(df)+1))).astype(str).apply('{:0>8}'.format
Related