Skip to main content
 首页 » 编程设计

python之使用多个字典填充 Pandas 数据框

2025年05月04日23unruledboy

我目前有一个数据框,希望使用成对的字典输入值。

# create count dataframe 
range_of_years = range(2012, 2017) 
topics = ['ecology','evolution','mathematics','biogeography','neutral theory'] 
topic_count_timeline = pandas.DataFrame(index = topics, columns = range_of_years) 
 
 
# dictionary pair 
count_dict = {2012: 10, 2013: 20, 2014: 12, 2015: 8, 2016: 9} 
paper_topics_dict = {'ecology': 0.7, 'neutral theory': 0.3} 

我想遍历字典键,选择具有与键对应的列和索引的数据框单元格,然后将字典值的乘积添加到该单元格。这样我就会得到结果数据框:

               2012 2013 2014 2015 2016 
ecology           7   14  8.4  5.6  7.7 
evolution       NaN  NaN  NaN  NaN  NaN 
mathematics     NaN  NaN  NaN  NaN  NaN 
biogeography    NaN  NaN  NaN  NaN  NaN 
neutral theory    3    6  3.6  2.4  3.3 

我打算使用多对字典(例如 count_dict 和 paper_topic_dict)更新 topic_count_timeline 数据帧,以便将新输入与之前的现有输入相加单元格而不是覆盖。

例如,如果使用另一对更新数据框...

# Additional dictionaries 
count_dict2 = {2012: 3, 2013: 2, 2014: 15, 2015: 16, 2016: 13} 
paper_topics_dict2 = {'mathematics': 0.6, 'neutral theory': 0.4} 

数据框看起来像这样:

               2012 2013 2014 2015 2016 
ecology           7   14  8.4  5.6  7.7 
evolution       NaN  NaN  NaN  NaN  NaN 
mathematics     1.8  1.2    9  9.6  5.4 
biogeography    NaN  NaN  NaN  NaN  NaN 
neutral theory  4.2  6.8  9.6  8.8  8.5 

谢谢。

请您参考如下方法:

我认为需要:

for k, v in paper_topics_dict.items(): 
    topic_count_timeline.loc[k] = v 
 
for k, v in count_dict.items(): 
    topic_count_timeline[k] *= v 
 
print (topic_count_timeline) 
               2012 2013 2014 2015 2016 
ecology           7   14  8.4  5.6  6.3 
evolution       NaN  NaN  NaN  NaN  NaN 
mathematics     NaN  NaN  NaN  NaN  NaN 
biogeography    NaN  NaN  NaN  NaN  NaN 
neutral theory    3    6  3.6  2.4  2.7 

但如果更好地处理字典对是为每一对更新 defaultdict,然后将其转换为 Series,对于 DataFrame 添加 unstack和 reindex对于缺少的列和索引值:

from collections import defaultdict 
 
count_dict = {2012: 10, 2013: 20, 2014: 12, 2015: 8, 2016: 9} 
paper_topics_dict = {'ecology': 0.7, 'neutral theory': 0.3} 
 
count_dict2 = {2012: 3, 2013: 2, 2014: 15, 2015: 16, 2016: 13} 
paper_topics_dict2 = {'mathematics': 0.6, 'neutral theory': 0.4} 
 
L = [(count_dict, paper_topics_dict), (count_dict2, paper_topics_dict2)] 
 
d = defaultdict(float) 
for a, b in L: 
    for k, v in b.items(): 
        for k2, v2 in a.items(): 
            d[(k, k2)] += v*v2 
 
df = pd.Series(d).unstack().reindex(index=topics, columns=range_of_years) 
print (df) 
                2012  2013  2014  2015  2016 
ecology          7.0  14.0   8.4   5.6   6.3 
evolution        NaN   NaN   NaN   NaN   NaN 
mathematics      1.8   1.2   9.0   9.6   7.8 
biogeography     NaN   NaN   NaN   NaN   NaN 
neutral theory   4.2   6.8   9.6   8.8   7.9