pandas dataframe concat is giving unwanted NA/NaN columns

北战南征 提交于 2021-01-29 15:47:34

问题


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

回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/23855777/pandas-dataframe-concat-is-giving-unwanted-na-nan-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!