Python 将列表列表放入 Pandas DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19112398/
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
Getting list of lists into pandas DataFrame
提问by Joop
I am reading contents of a spreadsheet into pandas. DataNitro has a method that returns a rectangular selection of cells as a list of lists. So
我正在将电子表格的内容读入熊猫。DataNitro 有一种方法可以将矩形单元格选择作为列表列表返回。所以
table = Cell("A1").table
gives
给
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
headers = table.pop(0) # gives the headers as list and leaves data
I am busy writing code to translate this, but my guess is that it is such a simple use that there must be method to do this. Cant seem to find it in documentation. Any pointers to the method that would simplify this?
我正忙着编写代码来翻译这个,但我猜想它是一个如此简单的使用,必须有方法来做到这一点。似乎无法在文档中找到它。任何指向可以简化此方法的指针?
采纳答案by EdChum
Call the pd.DataFrame
constructor directly:
pd.DataFrame
直接调用构造函数:
df = pd.DataFrame(table, columns=headers)
df
Heading1 Heading2
0 1 2
1 3 4
回答by Shoresh
With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:
使用上面 EdChum 解释的方法,列表中的值显示为行。要将列表的值显示为 DataFrame 中的列,只需使用 transpose() 如下:
table = [[1 , 2], [3, 4]]
df = DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']
The output then is:
然后输出是:
Heading1 Heading2
0 1 3
1 2 4
回答by YOBEN_S
Even without pop
the list we can do with set_index
即使没有pop
我们可以做的清单set_index
pd.DataFrame(table).T.set_index(0).T
Out[11]:
0 Heading1 Heading2
1 1 2
2 3 4
Update from_records
更新 from_records
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]:
Heading1 Heading2
0 1 2
1 3 4