gpt4 book ai didi

python - 转换 pandas.DataFrame 中的元组列表

转载 作者:行者123 更新时间:2023-12-02 03:23:27 25 4
gpt4 key购买 nike

我有三个元组列表,这些列表的第一个元素是年份,如下所示。

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

最佳答案

您可以为每个列表创建一个新的DataFrame,并使用merge 方法合并它们。

import pandas as pd 

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)]

df = (pd.DataFrame(data=list1, columns=["year", "list1"])
.merge(pd.DataFrame(data=list2, columns=["year", "list2"]), on="year")
.merge(pd.DataFrame(data=list3, columns=["year", "list3"]), on="year"))

关于python - 转换 pandas.DataFrame 中的元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60700295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com