1

I have a data frame

df = pd.DataFrame(carData)
df.column['models']
#df.ffill() This is where i need to fill the amount of columns i want to add with previous value

The data looks something like

          models
1         honda
2         ford
3         chevy

I want to add an index but keep it numerical up to a certain number and forward fill the models column to the last value. so for example the dataset above has 3 entries, I want to add an have a total of 5 entries it should look something like

          models
1         honda
2         ford
3         chevy
4         chevy
5         chevy
0

2 Answers 2

2

Using df.reindex() and df.ffill()

N= 5
df.reindex(range(N)).ffill()

    models
0   honda
1   ford
2   chevy
3   chevy
4   chevy
Sign up to request clarification or add additional context in comments.

Comments

2

Use reindex with method='ffill' or add ffill:

N = 5
df = df.reindex(np.arange(1, N + 1), method='ffill')
#alternative
#df = df.reindex(np.arange(1, N + 1)).ffill()
print (df)
  models
1  honda
2   ford
3  chevy
4  chevy
5  chevy

If default RangeIndex:

df = df.reset_index(drop=True)

N = 5
df = df.reindex(np.arange(N), method='ffill')
#alternative
#df = df.reindex(np.arange(N)).ffill()
print (df)
  models
0  honda
1   ford
2  chevy
3  chevy
4  chevy

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.