Joe
Joe

Reputation: 12417

Add empty row with index in a Pandas dataframe

In all the examples and answers on here that I've seen, if there is the need to add an empty row ina Pandas dataframe, all use:

ignore_index=True

What should I do if i want to leave the current index, and append an empty row to the dataframe with a given index?

Upvotes: 3

Views: 12131

Answers (3)

Harikishan R. Ellamla
Harikishan R. Ellamla

Reputation: 71

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.loc[len(df)] = pd.Series()

or use this with insert values

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.loc['Yourindex','A'] = 20

Upvotes: 1

HandyManDan
HandyManDan

Reputation: 478

I use this approach...

df = pd.DataFrame({'A' : ['one', 'one', 'two'] ,
                   'B' : ['Aa', 'Bb', 'Cc'] })
new_df = pd.concat([df, pd.DataFrame(index=pd.Index(['New Index']))])

Upvotes: 0

BENY
BENY

Reputation: 323226

We using reindex

df.reindex(df.index.values.tolist()+['Yourindex'])
Out[1479]: 
             A    B
0          one   Aa
1          one   Bb
2          two   Cc
Yourindex  NaN  NaN

Data input

df = pd.DataFrame({'A' : ['one', 'one', 'two'] ,
                   'B' : ['Aa', 'Bb', 'Cc'] })

Upvotes: 7

Related Questions