【发布时间】:2018-09-27 14:37:13
【问题描述】:
我目前有一个数据框并希望使用成对的字典输入值。
# 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
谢谢。
【问题讨论】:
-
字典对在列表中吗?例如在
L = [(count_dict, paper_topics_dict), (count_dict2, paper_topics_dict2)]? -
请从
I intend to update the topic_count_timeline dataframe using many pairs中删除以结束,因为接受答案是不行的。然后一切都很好,我也可以删除我的答案更新。谢谢。
标签: python python-3.x pandas dictionary dataframe