简体   繁体   English

将Numpy向量转换为列,熊猫

[英]Convert numpy vectors to columns, pandas

I have a numpay array with shape of (14,50176), which looks like this. 我有一个形状为(14,50176)的numpay数组,看起来像这样。

[[219 220 221 ...  32  33  34]
 [154 152 149 ...  15  15  15]
 [205 202 192 ... 183 183 179]
 ...
 [  6   7   7 ...  24  24  25]
 [239 245 246 ... 101 117 128]
 [ 21  44  89 ... 120 120 121]]

Now i want to convert this 14 vectors to column in pandas. 现在我想将这14个向量转换为熊猫列。 it suppose to look somrthing like this 它看起来像这样

 vectors
0 [219 220 221 ...  32  33  34]
1 [154 152 149 ...  15  15  15]
2 [205 202 192 ... 183 183 179]
.    ...
3 [  6   7   7 ...  24  24  25]
4 [239 245 246 ... 101 117 128]
5 [ 21  44  89 ... 120 120 121]

You can convert values to list s, but then lost vectorized functions in pandas: 您可以将值转换为list ,但随后会丢失熊猫中的矢量化函数:

a = np.array(
[[219,220,221,32,  33,  34],
 [154,152,149, 15, 15 ,15],
 [205,202,192, 183, 183, 179],
 [ 6, 7, 7, 24, 24, 25],
 [239, 245,246, 101, 117,128],
 [21, 44, 89, 120, 120,121]])


df = pd.DataFrame({'vectors':a.tolist()})
print (df)
                          vectors
0     [219, 220, 221, 32, 33, 34]
1     [154, 152, 149, 15, 15, 15]
2  [205, 202, 192, 183, 183, 179]
3           [6, 7, 7, 24, 24, 25]
4  [239, 245, 246, 101, 117, 128]
5     [21, 44, 89, 120, 120, 121]

So better is convert it to DataFrame : 更好的方法是将其转换为DataFrame

df = pd.DataFrame(a)
print (df)
     0    1    2    3    4    5
0  219  220  221   32   33   34
1  154  152  149   15   15   15
2  205  202  192  183  183  179
3    6    7    7   24   24   25
4  239  245  246  101  117  128
5   21   44   89  120  120  121

You probably want this, assuming you mean 14 rows and 1 column: 假设您要表示14行和1列,则可能需要这样做:

pd.DataFrame(array).apply(list, axis=1)

If you mean 50176 rows and 1 column, then change it to this: 如果要表示50176行和1列,则将其更改为:

pd.DataFrame(array).T.apply(list, axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM