我试图将数据帧存储到 hdf5 文件中,但是当我输入命令时
subInfo.to_hdf('storage.h5', 'd1', mode = 'a', append = True, format =
'table')
我收到错误消息:
Cannot serialize the column [pairs] because its data contents are [mixed]
object dtype
仅供引用,在我正在使用的数据框中,'pairs'
列仅包含长度为 2 的元组。如何解决这个问题?
示例数据:
pairs r r1
0 (179, 180) 0.928479 [17.671, 19.8573, 27.1782]
1 (179, 445) 21.189453 [17.671, 19.8573, 27.1782]
2 (179, 1052) 25.448198 [17.671, 19.8573, 27.1782]
3 (179, 1683) 16.970432 [17.671, 19.8573, 27.1782]
4 (179, 1684) 16.927219 [17.671, 19.8573, 27.1782]
5 (179, 1852) 8.293519 [17.671, 19.8573, 27.1782]
最佳答案
如果这不是问题,您可以简单地将 pandas 数据帧的数据类型转换为字符串,然后它将根据需要进行存储。
此外,如果数据是 int 和 float,您可以使用相同的代码将数据帧转换为相同类型的数据类型。
subInfo.astype(str).to_hdf('storage.h5', 'd1', mode = 'a', append = True, format = 'table')
您可以使用以下代码将列 r1 中的列表拆分为不同的列:
subInfo[["new1","new2","new3"]]=pd.DataFrame(subInfo.r1.values.tolist(),index=subInfo.index)
请记住,列数应等于列表或元组中的元素
类似地,您也可以使用类似的代码将第一列命名对中的元组拆分为两个不同的列:
subInfo[["new4","new5"]]=pd.DataFrame(subInfo.pairs.values.tolist(),index=subInfo.index)
关于python - Pandas 错误 - 为什么我的对象是混合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51469249/