循环将字典追加到pandas数据框

循环将字典追加到pandas数据框

本文介绍了循环将字典追加到pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在循环中创建一个字典,并将它们附加到具有匹配的dict关键字名和数据帧的列名的pandas数据帧中.每次迭代中字典的键值对可能不同.开头已定义了一个空的熊猫数据框df_podcast,并在字典中包含了所有可能的键.

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 ############

我将podcast_dict附加到df_podcast.播客实际上是一个列表列表,在这里我只考虑列表的第一行

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

推荐答案

您需要:

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

这篇关于循环将字典追加到pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:26