1

I am trying to create a file with several lines as header and append a column of numbers. I am having some issue appending a numpy.matrix after a header. I wrote a code as belowenter image description here

import numpy as np
import pandas as pd
import xlrd

df = pd.read_csv('Region_SGeMS.csv', header=None)

matrix = np.asmatrix(df)

#print(matrix)

s = np.shape(matrix)
print(s)
row = s[0]
col = s[1]

a = np.flip(matrix, 0)

b = np.reshape(a, (400, 1))

print(b)

f = open('Region.txt', 'w')

f.write(str(s[0]))
f.write(' ')
f.write(str(s[1]))
f.write(' 1 \n')
f.write('1 \n')
f.write('facies \n')

with open('Region.txt', 'a+') as outfile:
    np.savetxt(outfile,b) 

However, the highlighted number should be 2, not 0. I also attached a screenshot of my original excel file. Here is a screenshot of my result

4
  • 1
    why not np.savetxt()? Commented Feb 21, 2019 at 2:50
  • he did, on the final line Commented Feb 21, 2019 at 3:27
  • What's b[:10] - i.e the first part of b? Commented Feb 21, 2019 at 4:06
  • You really shouldn't use numpy.matrix objects, stick to normal multi-dimensional arrays. Commented Feb 21, 2019 at 21:33

2 Answers 2

1

Note that numpy.savetxt will append a header string to the file for you if you let it. For instance:

import numpy as np
# Recreate the original csv data
one_block = np.ones((10,10))
A   = np.block([ [0*one_block,one_block],[2*one_block,3*one_block] ])
M,N = A.shape
# Recreate b
a   = np.flip(A,0)
b   = a.reshape(400,1)
hdr_str = """{M:d} {N:d} 1
1
facies""".format(M=M,N=N)
outfile = 'Region.txt'
np.savetxt(outfile,b,header=hdr_str,comments='')

Below is a screenshot of my attempt at recreating your problem. There is no spurious 0.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

My b vector should start with a 2. I attached a screenshot of my original excel file. Please have a look.
I guess the issue may be related to the 'with open' command. Nevertheless, thank you for your help.
0
f = open('Region.txt', 'w')
f.write('first line \n')
f.write('second line \n')
f.close()

with open('Region.txt', 'a+') as outfile:
    np.savetxt(outfile,np.random.rand(10,3)) 

2 Comments

i assumed since the question is about appending, that you first want a txt file, and then later append a np array to it...
The issue is that there is a weird 0 at the beginning of my array but it should be a 2. I also noticed that if I put np.savetxt(outfile, b, fmt='%0.4f'), I will lose some of my data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.