[英]how to convert a panda dataframe column containing string object to a numpy array?
please i'am working on a project and i have to do some data preprocessing i have a dataframe that looks like this (this is just an example for simplification请我正在做一个项目,我必须做一些数据预处理我有一个看起来像这样的 dataframe(这只是一个简化的例子
index | pixels
0 | 10 20 30 40
1 | 11 12 13 14
and I want to convert it to a np array of shape (2,2,2,1) the type of the pixels column is object is there any solution to do that without loops cause I have a 28k rows data frame with big images?我想将它转换为形状 (2,2,2,1) 的 np 数组,像素列的类型是 object 是否有任何解决方案可以在没有循环的情况下做到这一点,因为我有一个带有大图像的 28k 行数据框? i have tried looping but it takes so long to execute on my machine
我试过循环,但在我的机器上执行需要很长时间
Use str.split
+ astype
+ to_numpy
+ reshape
:使用
str.split
+ astype
+ to_numpy
+ reshape
:
a = (
df['pixels'].str.split(' ', expand=True)
.astype(int).to_numpy()
.reshape((2, 2, 2, 1))
)
a
: a
:
[[[[10]
[20]]
[[30]
[40]]]
[[[11]
[12]]
[[13]
[14]]]]
Complete Working Example:完整的工作示例:
import pandas as pd
df = pd.DataFrame({'pixels': ['10 20 30 40', '11 12 13 14']})
a = (
df['pixels'].str.split(' ', expand=True)
.astype(int).to_numpy()
.reshape((2, 2, 2, 1))
)
print(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.