如何在 Python 中将元组元组转换为 pandas.DataFrame?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33700626/
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
How to convert tuple of tuples to pandas.DataFrame in Python?
提问by Oleg Melnikov
No offence, if the questions is too basic. Let me know if you need more information.
没有冒犯,如果问题太基本。如果您需要更多信息,请与我们联系。
I am looking for an idea to convert square-form tuple of tuples to pandas.DataFrame in a clean/efficient/pythonic way, i.e. from
我正在寻找一个想法,以干净/高效/pythonic的方式将元组的方形元组转换为pandas.DataFrame,即从
s =((1,0,0,0,),(2,3,0,0,),(4,5,6,0,),(7,8,9,10,))
to pandas.DataFrame
like
到pandas.DataFrame
像
1 2 3 4
1 1 0 0 0
2 2 3 0 0
3 4 5 6 0
4 7 8 9 10
Naturally, this list can grow with more zeros appended in the upper-triangular (if we think of s as a tuple of rows).
自然地,这个列表可以随着在上三角形中附加更多的零而增长(如果我们将 s 视为行的元组)。
DataFrame(t)
seems to fail.
DataFrame(t)
似乎失败了。
采纳答案by furas
import pandas as pd
s = ((1,0,0,0,),(2,3,0,0,),(4,5,6,0,),(7,8,9,10,))
print pd.DataFrame(list(s))
# 0 1 2 3
# 0 1 0 0 0
# 1 2 3 0 0
# 2 4 5 6 0
# 3 7 8 9 10
print pd.DataFrame(list(s), columns=[1,2,3,4], index=[1,2,3,4])
# 1 2 3 4
# 1 1 0 0 0
# 2 2 3 0 0
# 3 4 5 6 0
# 4 7 8 9 10
回答by unutbu
Pass a listof tuples instead of a tuple of tuples:
传递元组列表而不是元组元组:
In [13]: pd.DataFrame(list(s))
Out[13]:
0 1 2 3
0 1 0 0 0
1 2 3 0 0
2 4 5 6 0
3 7 8 9 10
pd.DataFrame(data)
follows different code paths when data
is a tuple as opposed to a list.
pd.DataFrame(data)
当data
是元组而不是列表时,遵循不同的代码路径。
Pandas developer Jeff Reback explains:
Pandas 开发人员Jeff Reback 解释说:
list-of-tuples is the specified type, tuple-of-tuple is not allowed as I think it can signify nested types that would require more parsing.
list-of-tuples 是指定的类型,tuple-of-tuple 是不允许的,因为我认为它可以表示需要更多解析的嵌套类型。