带有标题的嵌套到Pandas Dataframe的列表 [英] Nested List to Pandas Dataframe with headers

查看:79
本文介绍了带有标题的嵌套到Pandas Dataframe的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我正在尝试做要举一个例子,我想从下面的表格中查找:

To borrow that example, I want to go from the form:

data = [['Name','Rank','Complete'],
               ['one', 1, 1],
               ['two', 2, 1],
               ['three', 3, 1],
               ['four', 4, 1],
               ['five', 5, 1]]

应输出:

 Name Rank Complete
  One    1        1
  Two    2        1
Three    3        1
 Four    4        1
 Five    5        1

但是,当我做类似的事情时:

However when I do something like:

pd.DataFrame(data)

我得到一个数据框,其中第一个列表应该是我的列名,然后每个列表的第一个元素应该是行名

I get a dataframe where the first list should be my colnames, and then the first element of each list should be the rowname

为澄清起见,我希望每个列表的第一个元素为行名.我正在抓取数据,因此采用了这种格式...

To clarify, I want the first element of each list to be the row name. I am scrapping data so it is formatted this way...

推荐答案

一种方法是将列名作为一个单独的列表,然后仅从pd.DataFrame-

One way to do this would be to take the column names as a separate list and then only give from 1st index for pd.DataFrame -

In [8]: data = [['Name','Rank','Complete'],
   ...:                ['one', 1, 1],
   ...:                ['two', 2, 1],
   ...:                ['three', 3, 1],
   ...:                ['four', 4, 1],
   ...:                ['five', 5, 1]]

In [10]: df = pd.DataFrame(data[1:],columns=data[0])

In [11]: df
Out[11]:
    Name  Rank  Complete
0    one     1         1
1    two     2         1
2  three     3         1
3   four     4         1
4   five     5         1


如果要将第一列Name列设置为索引,请使用


If you want to set the first column Name column as index, use the .set_index() method and send in the column to use for index. Example -

In [16]: df = pd.DataFrame(data[1:],columns=data[0]).set_index('Name')

In [17]: df
Out[17]:
       Rank  Complete
Name
one       1         1
two       2         1
three     3         1
four      4         1
five      5         1

这篇关于带有标题的嵌套到Pandas Dataframe的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆