2017-09-07 39 views
1

我想将一个pandas DataFrame存储到一个CSV文件中。 DataFrame有两列:第一列有字符串,而第二列存储几个数组。熊猫写入到csv而不是数组的字符串

这里的问题是,而不是存储的字符串,每行一个数组中,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

希望的输出将是'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 ...'首先是字符串,然后是数组中包含的所有数字。 –

+0

我不认为我能够通过解析字符串来恢复数组,因为它存储'...'而不是内容 –

+0

哦,我明白了,我以为'...'是由您添加的! – IanS

回答

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()