python - 转换 pandas.DataFrame 中的元组列表
问题描述
我有三个元组列表,这些列表的第一个元素是一年,如下所示。
list1 = [
('2010', 1783675.0), ('2011', 1815815.0), ('2012', 1633258.0), ('2013', 1694062.0), ('2014', 1906527.0),
('2015', 1908661.0), ('2016', 2492979.0), ('2017', 2846997.0), ('2018', 2930313.0), ('2019', 2654724.0)
]
list2 = [
('2010', 302816.0), ('2011', 229549.0), ('2012', 323063.0), ('2013', 285066.0), ('2014', 282003.0),
('2015', 354500.0), ('2016', 275383.0), ('2017', 322074.0), ('2018', 366909.0), ('2019', 297942.0)
]
list3 =[
('2010', 149036.0), ('2011', 144112.0), ('2012', 173944.0), ('2013', 205724.0), ('2014', 214019.0),
('2015', 261462.0), ('2016', 260646.0), ('2017', 279267.0), ('2018', 288120.0), ('2019', 277106.0)
]
我想使用这些列表创建一个 pandas.DataFrame ,将年份设置为行索引:
list1 list2 list3
2010 1783675.0 302816.0 149036.0
2011 1815815.0 229549.0 144112.0
2012 1633258.0 323063.0 173944.0
2013 1694062.0 285066.0 205724.0
2014 1906527.0 282003.0 214019.0
2015 1908661.0 354500.0 261462.0
2016 2492979.0 275383.0 260646.0
2017 2846997.0 322074.0 279267.0
2018 2930313.0 366909.0 288120.0
2019 2654724.0 297942.0 277106.0
解决方案
已提供答案的另一种选择:python 的defaultdict可以简化在将数据读入数据帧之前将数据集中到一个字典中的过程:
from collections import defaultdict
from itertools import chain
#chain the lists into one, then
#get all the similar values into one list:
d = defaultdict(list)
for k, v in chain(list1,list2,list3):
d[k].append(v)
#read the data into a pandas dataframe:
df = pd.DataFrame.from_dict(d, orient='index', columns=['list1','list2','list3'])
list1 list2 list3
2010 1783675.0 302816.0 149036.0
2011 1815815.0 229549.0 144112.0
2012 1633258.0 323063.0 173944.0
2013 1694062.0 285066.0 205724.0
2014 1906527.0 282003.0 214019.0
2015 1908661.0 354500.0 261462.0
2016 2492979.0 275383.0 260646.0
2017 2846997.0 322074.0 279267.0
2018 2930313.0 366909.0 288120.0
2019 2654724.0 297942.0 277106.0
推荐阅读
- flutter - SharedPreferences File Path Stored 无法加载(Flutter Dart)
- android - 使用 android 导航的多个活动
- couchbase - 通过 Rest api 启用配置文件在通过 Rest Api 获取活动请求时不提供 phaseTimes
- reactjs - React-Scripts 无法在运行 WSL Ubuntu 的 Windows 上构建
- java - 当我将它添加到视频纹理视图 xml 文件时出现此错误(java.lang.BootstrapMethodError:来自调用站点#72 引导方法的异常)
- css - 包含 css 到 React 编译失败
- jquery - 如何在 chart.js 工具提示内容上隐藏标签数据?
- php - 为什么 Laravel 表单无法到达 URL,并以空消息重定向回来
- node.js - VPC 内 Lambda 的 SQS 超时
- postgresql - 使用 COPY 导入超过 1,000 个格式化数字的问题