【问题标题】:How to convert list of lists into a Pandas dataframe in python如何在 python 中将列表列表转换为 Pandas 数据框
【发布时间】:2021-03-03 03:28:30
【问题描述】:

我有一个如下列表,需要将其转换为 pandas 数据框。

mylist = [[2000, 0.5, 0.3, 0.8, 0.9, 0.8], [2001, 0.5, 0.6, 0.8, 0.9, 0.9], [2002, 0.5, 0.3, 0.8, 0.8, 0.8], [2003, 0.9, 0.9, 0.9, 0.9, 0.8]]
columns = ['year', 'score_1', 'score_2', 'score_3', 'score_4', 'score_5']

我希望数据框如下。

    year score_1 score_2 score_3 score_4 score_5
0    2000   0.5    0.3     0.8      0.9     0.8
1    2001   0.5    0.6     0.8      0.9     0.9
2    2002   0.5    0.3     0.8      0.8     0.8
3    2003   0.9    0.9     0.9      0.9     0.8

目前,我正在遵循以下代码。但它需要将我原来的“mylist”数据重组为“year”和“scores”。

pd.DataFrame(data=[scores],index=[year],columns=columns)

因此,我想知道在 pandas 中是否有任何简单的方法可以做到这一点。

如果需要,我很乐意提供更多详细信息。

【问题讨论】:

  • 我觉得你需要pd.DataFrame(mylist, columns=columns)

标签: python pandas


【解决方案1】:

如果只需要列通过mylist:

df = pd.DataFrame(mylist,columns=columns)
print (df)

   year  score_1  score_2  score_3  score_4  score_5
0  2000      0.5      0.3      0.8      0.9      0.8
1  2001      0.5      0.6      0.8      0.9      0.9
2  2002      0.5      0.3      0.8      0.8      0.8
3  2003      0.9      0.9      0.9      0.9      0.8

但如果需要按年索引,请使用 DataFrame.from_dict 的字典理解:

df = pd.DataFrame.from_dict({x[0]: x[1:] for x in mylist},columns=columns[1:], orient='index')
print (df)

      score_1  score_2  score_3  score_4  score_5
2000      0.5      0.3      0.8      0.9      0.8
2001      0.5      0.6      0.8      0.9      0.9
2002      0.5      0.3      0.8      0.8      0.8
2003      0.9      0.9      0.9      0.9      0.8

如果需要设置索引名称添加DataFrame.rename_axis:

d = {x[0]: x[1:] for x in mylist}
df = pd.DataFrame.from_dict(d,columns=columns[1:], orient='index').rename_axis(columns[0])
print (df)

      score_1  score_2  score_3  score_4  score_5
year                                             
2000      0.5      0.3      0.8      0.9      0.8
2001      0.5      0.6      0.8      0.9      0.9
2002      0.5      0.3      0.8      0.8      0.8
2003      0.9      0.9      0.9      0.9      0.8

【讨论】:

  • 谢谢!!你的解决方案对我有用!
猜你喜欢
  • 2021-03-22
  • 2021-09-27
  • 2017-06-22
  • 2018-10-30
  • 2022-06-16
  • 1970-01-01
  • 2016-02-05
  • 2020-09-02
  • 2021-01-22
相关资源
最近更新 更多