我想将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')
关于这里有什么问题的想法以及为什么它存储字符串而不是数组包含的一堆数字?
提前致谢!
答案 0 :(得分:1)
解决方案是序列化数据框中的数组。
# overwrites original arrays!
df['arrays'] = df['arrays'].apply(lambda a: ' '.join(map(str, a)))
快速举例:
s = pd.Series([np.arange(100, 200), np.arange(200, 300)])
s.apply(lambda a: ' '.join(map(str, a))).to_csv()