将元组转换为数据帧(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!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 barI 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!最满意答案
您可以使用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 barYou 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更多推荐
发布评论