Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫将字符串写入csv而不是数组_Python_Pandas_Csv - Fatal编程技术网

Python 熊猫将字符串写入csv而不是数组

Python 熊猫将字符串写入csv而不是数组,python,pandas,csv,Python,Pandas,Csv,我想将熊猫数据帧存储到CSV文件中。DataFrame有两列:第一列有字符串,第二列存储多个数组 这里的问题是,CSV文件不是按每行存储字符串和数组,而是按以下方式按每行存储两个字符串: 0004d4463b50_01.jpg,"[ 611461 44 613328 ..., 5 1767504 19]" 以下是我的代码示例: rle = [] # run test loop with a progress bar for i, (images, _) in

我想将熊猫数据帧存储到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()

所需输出为
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
\uuu str\uuuu
方法(就像如果将执行
打印(rle[0])
)您是对的,它只适用于numpy数组。如果您将它们转换为列表,它应该可以工作。