我想将 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')
关于这里出了什么问题以及为什么它存储字符串而不是数组包含的一堆数字有什么想法吗?
提前致谢!
最佳答案
解决方案是序列化数据帧中的数组。
# 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()
关于python - Pandas 将字符串写入 csv 而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46098401/