1

I have a DataFrame like this:

  a b
A 1 0
B 0 1

and I have an array ["A","B","C"].

From these, I want to create a new DataFrame like this:

  a   b
A 1   0
B 0   1
C NaN NaN

How can I do this?

2 Answers 2

4

Assuming I understand what you're after (setting aside weird duplicated-index cases), one way is to use loc to index into your frame:

>>> df = pd.DataFrame({'a': {'A': 1, 'B': 0}, 'b': {'A': 0, 'B': 1}})
>>> arr = ["A", "B", "C"]
>>> df
   a  b
A  1  0
B  0  1
>>> df.loc[arr]
    a   b
A   1   0
B   0   1
C NaN NaN
Sign up to request clarification or add additional context in comments.

Comments

2

Create an DataFrame with only index=['C'] and concat:

df = pd.DataFrame({'a': {'A': 1, 'B': 0}, 'b': {'A': 0, 'B': 1}}
df = pd.concat([df, pd.DataFrame(index=['C'])])

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.