Home > database >  save dataframe containing lists as csv file
save dataframe containing lists as csv file

Time:12-16

I have created DataFrame as the following

df = pd.DataFrame({'name': imgname, 'pose': pose})

where imgname is a list of string such as ['image1','image2' ...] the pose is a list of list such as pose = [array([ 55.77614093, 8.45208199, 2.69841043, 2.17110961]), array([ 66.61236215, 5.87653161, -31.70704038, -21.68979529])]

I use this line to write the Dataframe to csv file

df.to_csv('dataset.csv',index = 'False')

However, the pose col is converted to a string with '\n' and extra spaces

How can I save the values as numbers in csv format

CodePudding user response:

For pose, you probably do not mean arrays as list of list. Your code would work if you remove the array part -

import pandas as pd    
imgname = ['image1','image2'] 
pose = [[ 55.77614093, 8.45208199, 2.69841043, 2.17110961],[6.61236215, 5.87653161, -31.70704038, -21.68979529]]
df = pd.DataFrame({'name': imgname, 'pose': pose})

df output -

name    pose
0   image1  [55.77614093, 8.45208199, 2.69841043, 2.17110961]
1   image2  [66.61236215, 5.87653161, -31.70704038, -21.68...

after that,

df.to_csv('dataset.csv',index = 'False')

works just fine.

CodePudding user response:

df = pd.DataFrame({'Data': [np.array([1, 2, 3, 4]), np.array([5,6,7,8])], 'IMAGE' : ['IMAGE1', 'IMAGE2']})
print (df)

df.to_csv('dataset.csv',index = 'False')

and the result is the following : csv file

  • Related