The Python Oracle

Appending to Pandas DataFrame with categorical columns

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open

--

Chapters
00:00 Appending To Pandas Dataframe With Categorical Columns
00:48 Accepted Answer Score 1
01:10 Thank you

--

Full question
https://stackoverflow.com/questions/4214...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas

#avk47



ACCEPTED ANSWER

Score 1


You have to keep the both data frames consistent. As you are converting the column a from first data frame as categorical, you need do the same for second data frame. You can do it as following-

import pandas as pd

df=pd.DataFrame([],columns=['a', 'b'])
df['a']=pd.Categorical([],[0, 1])

new_df=pd.DataFrame.from_dict({'a':[0,1,1,1,0,0],'b':[1,1,8,4,0,0]})
new_df['a'] = pd.Categorical(new_df['a'],[0, 1])

df.append(new_df, ignore_index=True)

Hope this helps.