1

What I'm trying to do is to create a dataframe based on a list as index and with a dataframe already determined:

df1:

index   flag   value
3       1      99
5       1      98
7       1      97

index list:

all_index = [1, 2, 3, 4, 5, 6, 7, 8, 9]

then get this output:

df2:

index   flag
1       NaN
2       NaN
3       1
4       NaN
5       1
6       NaN
7       1
8       NaN

I was trying to do it in this way but doesn't works:

df2 = df1.loc[all_index]['flag']

3 Answers 3

1

use reindex

df.set_index('index').reindex(all_index)
Sign up to request clarification or add additional context in comments.

Comments

0

You just need reindex:

df2 = df1.reindex(all_index)["flag"]

Comments

0

If you want to get the exact layout (as a dataframe instead of a series), you can use .reindex() in this way:

df2 = df1.reindex(all_index)['flag'].to_frame()

Or

df2 = df1.reindex(all_index)[['flag']] 

Result:

print(df2)

   flag
1   NaN
2   NaN
3   1.0
4   NaN
5   1.0
6   NaN
7   1.0
8   NaN
9   NaN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.