[英]Converting tuple into dataframe
我有一個這樣的元組:
x=(('a', 'b'), ('foo', 'bar'))
我想將其變成這樣的DataFrame:
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!
您可以使用list(sum(x, ()))
來展平tuple
的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
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.