python - Pandas 将字符串写入 csv 而不是数组

标签 python pandas csv

我想将 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/

相关文章:

python - 验证 JSON 中的多个节点?

Python IO 大师 : what are the differences between these two methods?

python - 在 Python Pandas 中连接大量 CSV 文件(30,000)

php - 如何使用 PHP 获取 CSV 文件中的总行数?

python - win32com dispatch 找不到已经打开的应用程序实例

带有下划线的Python lambda作为参数?

javascript - 如何将带有日期的 JSON 文件加载到 Google Charts

Python:有条件地比较 CSV 行值

python - Pandas :将日期范围解压缩为单个日期

python - 如何将 pandas DataFrame 的日期时间索引作为 isoDate 类型的字段插入 mongodb