Append dictionary to pandas dataframe in a loop

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

I have a requirement to create a dictionary within a loop and append them to a pandas data frame with matching key name of dict and column name of data frame. The key value pairs of dictionary in each iteration could be different. An empty pandas data frame df_podcast have been defined at the beginning with all possible keys in the dictionary.

Below is the sample of a code which is not completed yet

df_podcast=pd.DataFrame(columns=podcast_cols)  podcast_dict={} for j in range(len(podcast[0])):     if podcast[0][j].tag=="key":         podcast_dict[podcast[0][j].text]=podcast[0][j+1].text ### Have to append dict to pandas df ############ 

I have append podcast_dict to df_podcast. Podcast is actually a list of lists, here I'm just considering only 1st row of the list

回答1:

You need:

df  = pd.DataFrame([podcast_dict], columns=podcast_dict.keys()) df_podcast = pd.concat([df_podcast, df], axis =0).reset_index() 


回答2:

IIUC:

What you need to do is to build your dictionary with your loop, then at then end of your loop, you can use your dictionary to create a dataframe with:

df1  = pd.DataFrame(podcast_dict) 

And append using pd.concat:

df_podcast = pd.concat([df_podcast, df1]) 


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