jason
jason

Reputation: 4439

pandas dataframe concat is giving unwanted NA/NaN columns

Instead of this example where it is horizontal After Pandas Dataframe pd.concat I get NaNs, I'm trying vertical:

import pandas
a=[['Date', 'letters', 'numbers', 'mixed'], ['1/2/2014', 'a', '6', 'z1'], ['1/2/2014', 'a', '3', 'z1'], ['1/3/2014', 'c', '1', 'x3']]
df = pandas.DataFrame.from_records(a[1:],columns=a[0])

f=[]
for i in range(0,len(df)):
    f.append(df['Date'][i] + ' ' + df['letters'][i])

df['new']=f

c=[x for x in range(0,5)]
b=[]
b += [['NA'] * (5 - len(b))]
df_a = pandas.DataFrame.from_records(b,columns=c)

df_b=pandas.concat([df,df_a], ignore_index=True)

df_b outputs same as df_b=pandas.concat([df,df_a], axis=0)

result:

     0    1    2    3    4      Date letters mixed         new numbers
0  NaN  NaN  NaN  NaN  NaN  1/2/2014       a    z1  1/2/2014 a       6
1  NaN  NaN  NaN  NaN  NaN  1/2/2014       a    z1  1/2/2014 a       3
2  NaN  NaN  NaN  NaN  NaN  1/3/2014       c    x3  1/3/2014 c       1
0   NA   NA   NA   NA   NA       NaN     NaN   NaN         NaN     NaN

desired:

       Date letters numbers mixed         new
0  1/2/2014       a       6    z1  1/2/2014 a
1  1/2/2014       a       3    z1  1/2/2014 a
2  1/3/2014       c       1    x3  1/3/2014 c
0  NA             NA      NA   NA  NA

Upvotes: 0

Views: 1086

Answers (2)

Happy001
Happy001

Reputation: 6383

If you are using latest versions, this gives you what you want

df.ix[len(df), :]='NA'

EDIT: OR if you want concat, when you define df_a, use columns of df as columns

df_a = pandas.DataFrame.from_records(b,columns=df.columns)

Upvotes: 1

Guillaume Jacquenot
Guillaume Jacquenot

Reputation: 11717

I would create a dataframe df_a with the correct columns directly.

With a little refactoring of your code, it gives

import pandas
a=[['Date', 'letters', 'numbers', 'mixed'], \
   ['1/2/2014', 'a', '6', 'z1'],\
   ['1/2/2014', 'a', '3', 'z1'],\
   ['1/3/2014', 'c', '1', 'x3']]
df = pandas.DataFrame.from_records(a[1:],columns=a[0])
df['new'] = df['Date'] + ' ' + df['letters']

n = len(df.columns)
b = [['NA'] * n]
df_a = pandas.DataFrame.from_records(b,columns=df.columns)
df_b = pandas.concat([df,df_a])

It gives

       Date letters numbers mixed         new
0  1/2/2014       a       6    z1  1/2/2014 a
1  1/2/2014       a       3    z1  1/2/2014 a
2  1/3/2014       c       1    x3  1/3/2014 c
0        NA      NA      NA    NA          NA

Eventually:

df_b = pandas.concat([df,df_a]).reset_index(drop=True)

It gives

       Date letters numbers mixed         new
0  1/2/2014       a       6    z1  1/2/2014 a
1  1/2/2014       a       3    z1  1/2/2014 a
2  1/3/2014       c       1    x3  1/3/2014 c
3        NA      NA      NA    NA          NA

Upvotes: 2

Related Questions