0

What is wrong with this saving of lists a, b to file please?

print(type(a[1]))
print(type(b))

gives

<class 'numpy.ndarray'>
<class 'numpy.ndarray'>

code:

with open("file.txt","w") as f:
    for (b,a[1]) in zip(b,a[1]):
        f.write("{0},{1}\n".format(b,a[1]))

error:

TypeError: object of type 'numpy.float64' has no len()

Thank you

EDIT

np.array(a.tolist())

Will lose the precision?

When I use

with open("file.txt","w") as f:
    for (x,y) in zip(b,a[1]):
        f.write("{0},{1}\n".format(b,a[1]))

the result is

[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ],[ 0.990688  0.991408  0.993574 ...,  1.03006   1.0326    1.0325  ]
[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ],[ 0.990688  0.991408  0.993574 ...,  1.03006   1.0326    1.0325  ]
[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ],[ 0.990688  0.991408  0.993574 ...,  1.03006   1.0326    1.0325  ]

print of lists a and b is:

[ 0.99572325  0.9969785   0.99801075 ...,  1.0412075   1.0423975   1.0432775 ]
[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ]

I would like a two columns in file - column with a and column with b as desired output.

Moe
  • 301
  • 2
  • 11
  • Numpy arrays are not lists. You cannot `zip` them. Also, your loop is wrong. – DYZ Nov 11 '19 at 06:21
  • The zip is ok, but don't use `b` and `a[1]` as the iteration variables. Use something like `x` and `y`. – hpaulj Nov 11 '19 at 06:58
  • Thank you for your advise, I editted the question – Moe Nov 11 '19 at 07:06
  • Could the file also be a csv or xlsx file? If so you could create a pandas dataframe from the to lists (in pandas series) and write this to an Excel or CSV File using dataframe.to_excel('Path'), or dataframe.to_csv('Path') – bimarian Nov 11 '19 at 09:21

1 Answers1

0

You could use the pandas library to do something like this:

import pandas as pd

#create two lists
a = list(range(10))
b = list(range(20, 30))

#create two series from the lists
series_a = pd.Series(a)
series_b = pd.Series(b)

#create a empty dataframe and name the columns
df = pd.DataFrame(columns=['a', 'b'])

#add the series to the dataframe by columns names df['cloumnname']
df['a'] = series_a
df['b'] = series_b

#wtiring the dataframe to an excel file
with pd.ExcelWriter('path/file.xlsx') as writer:
    df.to_excel(writer, sheet_name='Sheet1')

Note this saves the result to an excel file, does it have to be txt file like you mentioned in your question? If so this link should help: Python, Pandas : write content of DataFrame into text File

bimarian
  • 130
  • 1
  • 11