pandas 熊猫数组到列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44270983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:42:24  来源:igfitidea点击:

Pandas array to columns

pythonpandasdataframe

提问by Red Hoar

Given

给定的

data= [
    (array([0,0,1]),1),
    (array([0,1,1]),1),
    (array([1,0,1]),0),
    (array([1,1,1]),1)    
]

How can you convert it to a Pandas DataFrame so that each column is separate?

如何将其转换为 Pandas DataFrame 以便每一列都是独立的?

A   B   C   Z
0   0   1   1
0   1   1   1
1   0   1   0
1   1   1   1

采纳答案by piRSquared

I'd use np.appendin a list comprehension

我会np.append在列表理解中使用

pd.DataFrame([np.append(*row) for row in data], columns=list('ABCZ'))

   A  B  C  Z
0  0  0  1  1
1  0  1  1  1
2  1  0  1  0
3  1  1  1  1

Or more efficiently with np.column_stackand zip

或者更有效地使用np.column_stackzip

pd.DataFrame(np.column_stack(list(zip(*data))), columns=list('ABCZ'))

   A  B  C  Z
0  0  0  1  1
1  0  1  1  1
2  1  0  1  0
3  1  1  1  1

Timing

定时

%timeit pd.DataFrame([np.append(*row) for row in data], columns=list('ABCZ'))
1000 loops, best of 3: 460 μs per loop

%timeit pd.DataFrame(np.column_stack(list(zip(*data))), columns=list('ABCZ'))
10000 loops, best of 3: 130 μs per loop

%timeit pd.DataFrame([e[0].tolist()+[e[1]] for e in data],columns=['A','B','C','Z'])
1000 loops, best of 3: 446 μs per loop

回答by Allen

Convert your array to a list of lists and then put it into a Dataframe.

将您的数组转换为列表列表,然后将其放入数据框。

pd.DataFrame([e[0].tolist()+[e[1]] for e in data],columns=['A','B','C','Z'])
Out[265]: 
   A  B  C  Z
0  0  0  1  1
1  0  1  1  1
2  1  0  1  0
3  1  1  1  1