[英]How to convert a pandas dataframe into one dimensional array?
I have a dataframe X
.我有一个数据框
X
。 I want to convert it into 1D array with only 5 elements.我想将它转换成只有 5 个元素的一维数组。 One way of doing it is converting the inner arrays to lists.
一种方法是将内部数组转换为列表。 How can I do that?
我怎样才能做到这一点?
0 1 2 3 4 5 0 1622 95 1717 85.278544 1138.964373 1053.685830 1 62 328 390 75.613900 722.588235 646.974336 2 102 708 810 75.613900 800.916667 725.302767 3 102 862 964 75.613900 725.870370 650.256471 4 129 1380 1509 75.613900 783.711111 708.097211
val = X.values
will give a numpy array. val = X.values
将给出一个 numpy 数组。 I want to convert the inner elements of the array to list.我想将数组的内部元素转换为列表。 How can I do that?
我怎样才能做到这一点? I tried this but failed
我试过了但失败了
M = val.values.tolist()
A = np.array(M,dtype=list)
N = np.array(M,dtype=object)
Here's one approach to have each row as one list to give us a 1D
array of lists -这是一种将每一行作为一个列表来为我们提供列表的一
1D
数组的方法 -
In [231]: df
Out[231]:
0 1 2 3 4 5
0 1622 95 1717 85.278544 1138.964373 1053.685830
1 62 328 390 75.613900 722.588235 646.974336
2 102 708 810 75.613900 800.916667 725.302767
3 102 862 964 75.613900 725.870370 650.256471
4 129 1380 1509 75.613900 783.711111 708.097211
In [232]: out = np.empty(df.shape[0], dtype=object)
In [233]: out[:] = df.values.tolist()
In [234]: out
Out[234]:
array([list([1622.0, 95.0, 1717.0, 85.278544, 1138.964373, 1053.6858300000001]),
list([62.0, 328.0, 390.0, 75.6139, 722.5882349999999, 646.974336]),
list([102.0, 708.0, 810.0, 75.6139, 800.916667, 725.302767]),
list([102.0, 862.0, 964.0, 75.6139, 725.87037, 650.256471]),
list([129.0, 1380.0, 1509.0, 75.6139, 783.7111110000001, 708.097211])], dtype=object)
In [235]: out.shape
Out[235]: (5,)
In [236]: out.ndim
Out[236]: 1
Have you tried to use df.as_matrix()
and then join rows?您是否尝试过使用
df.as_matrix()
然后加入行?
Example:例子:
L=[]
for m in df.as_matrix().tolist():
L += m
If it has only one column, you can try this如果它只有一列,你可以试试这个
op_col = []
for i in df_name['Column_name']:
op_col.append(i)
print(op_col)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.