Dear Community,
I would like to export a dataframe with empty cells, floats and strings to a file.txt. I have tried several functions such as to_csv, np.save and f.write. The best so far was f.write. However, I cannot get format that I want.
I can export without problems the first two lines. The problem is the float part of the dataframe. This is the code that I am using:
Kind regards,
PD: I am aware that the code looks dirty. There is problably another way to write the same script, but clear and clean. I am open to new ideas. I would like to improve my python skills step by step.
I would like to export a dataframe with empty cells, floats and strings to a file.txt. I have tried several functions such as to_csv, np.save and f.write. The best so far was f.write. However, I cannot get format that I want.
I can export without problems the first two lines. The problem is the float part of the dataframe. This is the code that I am using:
import pandas as pd
import numpy as np
X=3
Y=3
# Create matrix with dimensions X,Y
lon=[[-180, -175, -170],[-180, -175, -170],[-180, -175, -170]]
#Create data and lon dataframe
data=pd.DataFrame([['gridtype=','curvilinear'],['gridsize=',X*Y]])
dslon=pd.DataFrame(lon)
#Create a columns of empty values with Y rows
emptycol=pd.DataFrame([['']]*Y)
#allocate the string 'xvals=' in the first cell
emptycol.iloc[0,0]='xvals='
#Merge dataframe empty col with dslon
horizontal_concat = pd.concat([emptycol, dslon],axis=1)
#Reset columns index
horizontal_concat.columns = range(horizontal_concat.columns.size)
#Merge the rows of horizontal_concat on the bottom of data and reset index
c_concat =pd.concat([data, horizontal_concat], axis=0)
c_concat.index = range(c_concat.index.size)
#Replace Nan values by empty cells
cc=c_concat.replace(np.nan,'')
#Write file into a data.txt
for j in range(0,5):
[line]=cc.iloc[[j]].values
with open('data.txt', 'a') as f:
if j <3:
for row in line:
f.write(str(row))
f.write('\n')
else:
line_h=np.empty((len(line[:])),dtype=object)
line_h[:]=line.reshape(1,-1)
for row in line_h:
f.writelines(str(row)+',')
f.write('\n')
f.close() I would like to export to this txt formatgridtype=curvilinear
gridsize= 9
xvals= -180, -175, -170,
-180, -175, -170,
-180, -175, -170, Thanks so much in advance for your help.Kind regards,
PD: I am aware that the code looks dirty. There is problably another way to write the same script, but clear and clean. I am open to new ideas. I would like to improve my python skills step by step.
