是否可以将2D数组作为2D数据帧的元素



我是一名学生,正在做视频编码器项目。我在txt文件中提取了像素值和其他信息(POC、x位置、y位置、高度、宽度(。我将使用h5py将这些数据转换为hdf5文件。但我想知道pandas甚至hdf5是否支持在pandas 2D数据帧中使用2D数组(像素值(。

例如,设p=[[1,2],[3,4]]作为我的像素值。我可以让我的数据帧像这样吗数据集[0]=[0(POC(,0(x(,O(y(,p(2D阵列像素值(]?或者它甚至可以用hdf5格式编写?

是的,你可以,这里有一个例子:

df = pd.DataFrame({'Col1':['a','b','c'],
'Col2':[{'a':[1,2,3]},{'b':[[2.1],[1]]},{'c':[{'test':'hello'}]}],
'Col3':[[[1,2],[3,4]],[[4],[5]],[[3,5,10],[9]]]})
df

输出:

df
Col1                          Col2               Col3
0      a              {'a': [1, 2, 3]}   [[1, 2], [3, 4]]
1      b           {'b': [[2.1], [1]]}         [[4], [5]]
2      c    {'c': [{'test': 'hello'}]}  [[3, 5, 10], [9]]

正如您所看到的,您可以在pandas数据帧中拥有列表、列表列表、字典、列表字典、字典列表等。

df.info()

输出:


<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
#   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
0   Col1    3 non-null      object
1   Col2    3 non-null      object
2   Col3    3 non-null      object
dtypes: int64(1), object(2)
memory usage: 200.0+ bytes
type(df.Col3[0])

输出:

list

下面是一个使用h5py创建HDF5文件并加载一些简单数据作为属性的示例。

import h5py
# pixel data to load to a dataset
p = [[1,2],[3,4]]
# attribute names and values:
attr_names = ['POC', "x_position", 'y_position', 'height', 'width']
POC = 10.
x_position = 100
y_position = 200  
height = 16.
width = 5.
with h5py.File('SO_71383695.h5', 'w') as h5w:
ds = h5w.create_dataset('pixel_data', data=p)
for name in attr_names:
ds.attrs[name] = eval(name)

with h5py.File('SO_71383695.h5') as h5r:    
p_data = h5r['pixel_data'][:] # to read into numpy array
print (p_data)
for name in h5r['pixel_data'].attrs.keys():
print(f"{name}: {h5r['pixel_data'].attrs[name]}")

您可以使用HDFView查看数据。输出:

[[1 2]
[3 4]]
POC: 10.0
height: 16.0
width: 5.0
x_position: 100
y_position: 200

最新更新