Reputation: 3577
I have a tuple like this:
x=(('a', 'b'), ('foo', 'bar'))
and I want to turn it into a DataFrame like this:
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!
Upvotes: 2
Views: 4198
Reputation: 4899
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
Upvotes: 1
Reputation: 42905
You can use list(sum(x, ()))
to flatten your tuple
of tuples
:
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
Upvotes: 3