简体   繁体   English

将元组转换为数据框

[英]Converting tuple into dataframe

I have a tuple like this: 我有一个这样的元组:

x=(('a', 'b'), ('foo', 'bar'))

and I want to turn it into a DataFrame like this: 我想将其变成这样的DataFrame:

One  Two   Three   Four
a    b     foo     bar

I have been trying to use this: 我一直在尝试使用此:

df = pd.DataFrame(x, columns=['One', 'Two', 'Three', 'Four])

but this error is returned: 但返回此错误:

runfile('D:/python codes/histo_matching.py', wdir='D:/python codes')
Traceback (most recent call last):

  File "<ipython-input-31-1104531b1d67>", line 1, in <module>
    runfile('D:/python codes/histo_matching.py', wdir='D:/python codes')

  File "C:\Users\Stefano\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)

  File "C:\Users\Stefano\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "D:/python codes/histo_matching.py", line 63, in <module>
    df = pd.DataFrame(x, columns=['One', 'Two', 'Three', 'Four'])

  File "C:\Users\Stefano\Anaconda\lib\site-packages\pandas\core\frame.py", line 291, in __init__
    raise PandasError('DataFrame constructor not properly called!')

PandasError: DataFrame constructor not properly called!

You can use list(sum(x, ())) to flatten your tuple of tuples : 您可以使用list(sum(x, ()))来展平tupletuples

x = (('a', 'b'), ('foo', 'bar'))
pd.DataFrame(data=list(sum(x, ())), index=['One', 'Two', 'Three', 'Four']).transpose()

  One Two Three Four
0   a   b   foo  bar
x=(('a', 'b'), ('foo', 'bar'))

foo = [[y] for a in x for y in a]
names = ["One", "Two", "Three", "Four"]

df = pd.DataFrame({names[ix]: foo[ix] for ix in range(4)})
df = df[names]

>>> print(df[names])
  One Two Three Four
0   a   b   foo  bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM