2015-12-30 114 views
1

我有這樣一個元組:轉換解析成數據幀

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

,我希望把它變成像這樣的數據幀:

One Two Three Four 
a b  foo  bar 

我一直在嘗試使用此:

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

但這個錯誤返回:

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! 

回答

2

您可以使用list(sum(x,()))扁平化的tuplestuple

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 
1
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