【发布时间】:2026-01-13 23:15:02
【问题描述】:
我想将 pandas DataFrame 存储到 CSV 文件中。 DataFrame 有两列:第一列包含字符串,第二列存储多个数组。
这里的问题是CSV文件不是每行存储一个字符串和一个数组,而是按以下方式每行有两个字符串:
0004d4463b50_01.jpg,"[ 611461 44 613328 ..., 5 1767504 19]"
我的代码示例可以在这里找到:
rle = []
# run test loop with a progress bar
for i, (images, _) in enumerate(loader):
# do some stuff here
# 'rle_local' is a ndarray with more than a thousand elemnts
rle.append(rle_local)
# 'names' contain the strings
df = pd.DataFrame({'strings': names, 'arrays': rle})
df.to_csv(file_path, index=False, compression='gzip')
关于这里出了什么问题以及为什么它存储字符串而不是数组包含的一堆数字有什么想法吗?
提前致谢!
【问题讨论】:
-
期望的输出是
00087a6bd4dc_01.jpg,879386 40 881253 141 883140 205 885009 17 885032 259 886923 308 888839 328 890754 340 892670 347 894587 352 896503 357 898420 360 900336 364 902253 367 904170 370 906086 374 ...首先是字符串,然后是数组中包含的所有数字。 -
我认为我无法通过解析字符串来恢复数组,因为它存储的是
...而不是内容 -
哦,我明白了,我以为
...是你添加的! -
我使用的是 pandas 0.20.3 和 python 3.6。我仔细检查了,
rle是一个 python 列表,而它的内容类型是ndarray。似乎它正在将 ndarray__str__方法存储在文件中(就像print (rle[0])一样) -
你说得对,它只适用于 numpy 数组。如果您将它们转换为列表,它应该可以工作。