将二维数组变成两列数据框 pandas [英] turning a two dimensional array into a two column dataframe pandas
问题描述
如果我具有以下内容,如何使pd.DataFrame()将此数组转换为具有两列的数据帧.最有效的方法是什么?我当前的方法涉及将每个副本创建为一系列,并从中创建数据框.
if I have the following, how do I make pd.DataFrame() turn this array into a dataframe with two columns. What's the most efficient way? My current approach involves creating copies out of each into a series and making dataframes out of them.
从此:
([[u'294 (24%) L', u'294 (26%) R'],
[u'981 (71%) L', u'981 (82%) R'],])
到
x y
294 294
981 981
而不是
x
[u'294 (24%) L', u'294 (26%) R']
我目前的做法.寻找更有效的东西
my current approach. Looking for something more efficient
numL = pd.Series(numlist).map(lambda x: x[0])
numR = pd.Series(numlist).map(lambda x: x[1])
nL = pd.DataFrame(numL, columns=['left_num'])
nR = pd.DataFrame(numR, columns=['right_num'])
nLR = nL.join(nR)
nLR
更新**
我注意到我的错误仅归结于当您pd.DataFrame()一个列表而不是一个序列时.当您从列表中创建数据框时,它会将项目合并到同一列中.列表不是这样.那以最有效的方式解决了我的问题.
I noticed that my error simply comes down to when you pd.DataFrame() a list versus a series. WHen you create a dataframe out of a list, it merges the items into the same column. Not so with a list. That solved my problem in the most efficient way.
推荐答案
In [172]: data = [[u'294 (24%) L', u'294 (26%) R'], [u'981 (71%) L', u'981 (82%) R'],]
In [173]: clean_data = [[int(item.split()[0]) for item in row] for row in data]
In [174]: clean_data
Out[174]: [[294, 294], [981, 981]]
In [175]: pd.DataFrame(clean_data, columns=list('xy'))
Out[175]:
x y
0 294 294
1 981 981
[2 rows x 2 columns]
这篇关于将二维数组变成两列数据框 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!