Python 带有标题的 Pandas 数据帧的嵌套列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32857544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested List to Pandas Dataframe with headers
提问by qwertylpc
Basically I am trying to do the opposite of How to generate a list from a pandas DataFrame with the column name and column values?
基本上,我试图做与如何从带有列名和列值的 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]]
which should output:
应该输出:
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
我得到一个数据框,其中第一个列表应该是我的列名,然后每个列表的第一个元素应该是行名
EDIT:
编辑:
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...
为了澄清,我希望每个列表的第一个元素是行名称。我正在报废数据,所以它的格式是这样的......
采纳答案by Anand S Kumar
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
-
一种方法是将列名作为一个单独的列表,然后只从第一个索引给出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
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 -
如果要将第一列的Name
列设置为索引,请使用该.set_index()
方法并发送用于索引的列。例子 -
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