nakaakist
nakaakist

Reputation: 358

Creating new pandas DataFrame from existing DataFrame and index

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?

Upvotes: 1

Views: 5421

Answers (2)

mgcdanny
mgcdanny

Reputation: 1202

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'])])

Upvotes: 2

DSM
DSM

Reputation: 353159

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

Upvotes: 4

Related Questions