len
len

Reputation: 807

export pandas dataframe with formatted columns

I have as example the following data file (data.txt), containing:

   1  7173024   8.114445 46.726944  310.0  254.0 A321 2
   1  7173085   8.303217 46.780174  310.0  250.8 A321 2
   1  7173146   8.489831 46.832840  310.0  106.0 A321 2

with the format:

column 1: %8d    
column 2: %8d    
column 3: %10.6f    
column 4: %9.6f    
column 5: %6.1f    
column 6: %6.1f    
column 7: %3s    
column 8: %1d

In between each column is an empty space " ".

I want to use Pandas to increase column 5 by 20 and save the columns in the same format ('%8d %8d %10.6f %9.6f %6.1f %6.1f %3s %1d') to another new file.

What I did:

import pandas as pd

df = pd.read_csv("data.txt",names=["a", "b", "c", "d", "e", "f", "g", "h"], sep="\s+")
df.loc[df["e"] > 0, "e"] = df["e"] + 20

df.to_csv("data_new.txt", sep=' ', index=False, header=False)

How can I export the data with pandas using the specific format?

Upvotes: 0

Views: 170

Answers (1)

len
len

Reputation: 807

A solution with numpy would be:

import numpy as np
np.savetxt('data_new.txt', df.values, fmt='%8d %8d %10.6f %9.6f %6.1f %6.1f %3s %1d')

Upvotes: 1

Related Questions